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"));