Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda