Unsure of how to approach Data Access Object/Layer in an Express / MongoDB Application Unsure of how to approach Data Access Object/Layer in an Express / MongoDB Application express express

Unsure of how to approach Data Access Object/Layer in an Express / MongoDB Application


Bit late to the party, but in my opinion the split should be that the Express handler deals with the HTTP request, and your other method deals with the database.

Expanding your original script and using callbacks:

//server.js...var dbApi = require('../data/db-api.js');...app.get('/api/user', (req, res) => {  try {    dbApi.getUsers((documents) => res.send(documents))  } catch (error) {    // or something along those lines    res.status(500).send({ error: error.message });  }});...//db-api.js...getUsers: function () {  MongoClient.connect(url, function (err, db) {  if (err) {    throw err;  }  db.collection(collections.Users)    .find({})    .toArray(function (error, documents) {      db.close();      if (error) {        throw error;      }      return documents;    });  });}

Sam H. is right as well, I'd promisify/async this so it becomes more intuitive, the current versions of the Mongodb client on node will return a promise if you don't supply a callback:

//server.js...const dbApi = require('../data/db-api.js');...app.get('/api/user', async (req, res) => {  try {    const documents = await dbApi.getUsers();    res.send(documents)  } catch (error) {    // or something along those lines    res.status(500).send({ error: error.message });  }});...//db-api.js...getUsers: async function () {  const db = await MongoClient.connect(url);  const collection = await db.collection(collections.Users);  const query = await collection.find({});  const documents = await query.toArray();  await db.close();  return documents;}

Or with Promises:

//server.js...const dbApi = require('../data/db-api.js');...app.get('/api/user', (req, res) => {  dbApi.getUsers()    .then(documents => res.send(documents))    .catch(error => res.status(500).send({ error: error.message })});...//db-api.js...getUsers: function () {  return MongoClient.connect(url)    .then(db => Promise.all([      db,      db.collection(collections.Users).find({}).toArray()    ]))    .then(([db, documents]) => Promise.all([documents, db.close()])    .then(([documents]) => documents)}


Well, you can use a promisified version of the mongo client, return the promise of that value, and use async/await. See, for example, this answer.