Home > Blockchain >  How to connect to a MongoDB asynchronously?
How to connect to a MongoDB asynchronously?

Time:03-01

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?

CodePudding user response:

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

CodePudding user response:

Try to await the createConnection:

async function station_list_all(dbname){

    return new Promise(async (resolve,reject) => {
            try {
                let connection = await 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;
            });

}
  • Related