Friday, 24 July 2020

Database Example

I am trying to find a good example of how a database should be handled in nodejs using mongodb.At the moment my DB calls are similar to this:function setCurrentDate(date){ return new Promise(function (resolve, reject) { try { MongoClient.connect(url, {useNewUrlParser: true}) .then((db) => { //Get the database let dbo = db.db('billboard'); let collection = dbo.collection('config'); collection.updateOne( { key: configKey}, {$set: { value: date }}, {upsert: true} ).then(() => { db.close().then(() => { resolve(true); }) }).catch((err) => { db.close().then(() => { reject(err); }); }); }); } catch (err) { reject(err); } }); } I am sure there are far better ways than calling the MongoClient.connect every single time and then adding all those closes manually. So I am looking to implement the DRY methodology but at the moment every single one of my DB methods starts with that MongoClient.connect and all of them have the db.close() littered through the call itself.I would greatly appreciate it if someone can point me in the right direction.

Submitted July 24, 2020 at 12:58PM by chamna312

No comments:

Post a Comment