Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

111
Vistas
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.

over 4 years ago · Santiago Trujillo
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda