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

195
Vistas
How to connect to a MongoDB asynchronously?

I have a MongoDB database. I'm using Javascript and Node.js (using Mangoose) to access this database. I need to return an array with the name of all the collections in the database. So I use a code that follows.

let connection = mongoose.createConnection(process.env.MONGODB_URI + "/" + dbname);

// Wait 10 seconds for Mongoose to establish the connection.
await new Promise(r => setTimeout(r, 10000));

return connection.db.collections()
       .then(stations=>stations.map(stations=>stations.collectionName))
       .catch(reason => {
                console.error("Error : "+reason);
                return null;
       });

The code above is working correctly. Now, I'm trying to do the same process asynchronously. For this, I am using the following code.

async function station_list_all(dbname){

    return new Promise((resolve,reject) => {
            try {
                let connection = mongoose.createConnection(process.env.MONGODB_URI + "/" + dbname);
                resolve(connection);
            }catch(err){
                reject(new Error("DB not found!"));
            }
        })
            .then(connection => connection.db)
            .then(db => db.collections())
            .then(stations=>stations.map(station=>station.collectionName))
            .catch(err => {
                console.error("Error : "+err);
                return null;
            });

}

Unfortunately, instead of the collection names, I get the message: Error : TypeError: Cannot read property 'collections' of undefined.

I think db is returning undefined, but... Shouldn't the code wait until db has a valid value?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try with async await:

try {
  await mongoose.connect('mongo url with db name');
  // other process
} catch (error) {
  handleError(error);
}

Or you can connect using callback:

try {
    mongoose.connect('mongo url with db name').then(()=>{
        // other process
    });  
} catch (error) {
    handleError(error);
}

In Same way you can try with promise also. There is no need use settimeout.

For More Ref Please visit: Mongoose Connections

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