Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
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.

about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!