Thursday, 27 April 2017

MongoDB connect to different database using rest api

I am trying to create simple rest api using express.js and mongodb.

For now I have post and get calls which are working fine but now I would like to create api call that return archived data.

Problem is that i am using one connection for database and I need another one only for this one archive call.

My connection looks like this:

var date = new Date();
var month= date.getUTCMonth() + 1;

var mongoose   = require('mongoose');
mongoose.connect('mongodb://localhost:27017/ranking-'+month); // connect to my database depending on month (ranking-1, ranking-2 etc)

I have simple get call:

router.route('/users')
.get(function(req, res) {
        User.find().sort({ points: '-1' }).exec(function(err, users) {

            if (err)
                res.send(err);

            res.json(users);
        });
});

Now I am trying to create exacty same call for archived data but with different route /month/id:

router.route('/archive/month/:id?')

.get(function(req, res) {
    //mongoose.connect('mongodb://localhost:27017/ranking-'+req.params.id); // not working
    User.find().sort({ points: '-1' }).exec(function(err, users) {

        if (err)
            res.send(err);

        res.json(users);

    });

});

I tried to simply add req.params.id to my connection but I get error: Error: Trying to open unclosed connection.

I tried to create different models with createConnection(); but I need exactly the same database with id passed by get call.



via omygoodness

No comments:

Post a Comment