Building an async / await Promise Based MongoDB Query Library

And importing them into your Express routes

Defining the Structure

routes/
db/
dbAuth.js
dbUser.js
...
auth.js
user.js
...

Creating the list of Mongo Exports

const { getSignedInUser, 
updateAuthToken,
validateAuthToken,
destroyAuthToken } = require('./db/dbAuth');
getSomethingFromMongo: async (arg1, arg2) => (await (() => (   new Promise((resolve, reject) => 
(clientConnect().then(client => {
const db = client.db('my-database');
//execute query and resolve promise...
})
))))()),

Breaking down the syntax

Brackets, and more brackets

A quick look at dbMongo.js

Importing and using your exports

const { getSignInUser } = require('./db/dbAuth');
router.post('/signin', (req, res, next) => {

getSignInUser(req.body.username).then(data => {

//handle data returned from Mongo

}).catch(e => {
next(e);
});
});
getSomethingFromMongo: async (arg1, arg2) => (await (() => (   new Promise((resolve, reject) => 
(clientConnect().then(client => {
const db = client.db('my-database'); //execute query and resolve promise...
})
))))()),

Continue Reading…

Programmer and Author. Director @ JKRBInvestments.com. Creator of LearnChineseGrammar.com for iOS.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store