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

205
Vistas
How to pass mongodb database connection through routes in Node?

I need to pass the connection to mongo from index.js to the other routes, I think it is possible to create a file with the instructions that define the connection with the database, so that I can recall it within the other routes, but I have no idea how it can be done. The other examples on this forum didn't help me a lot. I will attach the code below.

//Database connection
mongoose.connect("mongodb://localhost:27017/codingWaifus", {useNewUrlParser: true}, function(err, db){
  if(err){
    console.log(err);
  }
  else{
    console.log("Connected to "+mongoose.connection.name+" on Port: "+mongoose.connection.port);
  }
});
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can do this in the following way:

db.js

const mongoose = require('mongoose');
const dotenv = require('dotenv').config();

const connectDB = () => {
    mongoose.connect(process.env.MONGODB_URI, {useNewUrlParser: true, useUnifiedTopology: true});

    mongoose.connection
    .once('open', () => { 
        console.log('Connection to the DB established');
    })
    .on('error', (err) => { 
        console.log('Error occured while connecting to the DB', err);
    })
}

module.exports = connectDB;

index.js

const connectDB = require('./db');
 
// Connecting to the DB
connectDB();

But why do you want to call the MongoDB connection again when you have already established the connection on the first place?

about 4 years ago · Juan Pablo Isaza Denunciar
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