1

I try to package the db connecting for more reusable. I want to achieve like :

const mongoPromise =MongoClient.connect(url,{ useNewUrlParser: true })
.then((client)=>{
      const db = client.db(dbName);

      // do something...

      client.close();
})
.catch(err=>console.log(err));

Thus, I can use it to other places:

//For example
//query
mongoPromise.then((db)=>db.collection('user').find().toArray())

//insert
mongoPromise.then((db)=>db.collection('test').insert({...}))

When query or insert finished , the MongoClient will be close


At first method,I just can figure out a solution by mixing callback and promise.

Is it not good for mixing callback and promise together?

// First method
const mongoPromiseCallback =(callback)=>MongoClient.connect(url,{ useNewUrlParser: true })
.then(async(client)=>{
      const db = client.db(dbName);
      await callback(db);
      console.log("close the client");
      client.close();
})
.catch(err=>console.log(err))

mongoPromiseCallback(db=>db.collection('user').find().toArray())
.then(res=>console.log(res)));


At the other method,I try to use only promise,but I don't know where can I close the client.

// the other method
const mongoPromise =MongoClient.connect(url,{ useNewUrlParser: true })
.then((client)=>{
      const db = client.db(dbName);
      return new Promise(function(resolve, reject) {
        resolve(db);
      });
})
.catch(err=>console.log(err));

mongoPromise.then(db=>db.collection('user').find().toArray())
.then(res=>console.log("res"));
John
  • 13
  • 3

1 Answers1

0

You can always reuse the db object you created in mongo. Here read this it'll answer the question How do I manage MongoDB connections in a Node.js web application?

Mehul Mittal
  • 134
  • 10