Node.js MongoDB Integration for Node.js/Express.js Querying your Mongo Database


Example

A simple GET request. Let's assume the Model from the example above is in the file ./db/models/Article.js.

const express = require('express');
const Articles = require('./db/models/Article');

module.exports = function (app) {
  const routes = express.Router();
  
  routes.get('/articles', (req, res) => {
    Articles.find().limit(5).lean().exec((err, doc) => {
      if (doc.length > 0) {
        res.send({ data: doc });
      } else {
        res.send({ success: false, message: 'No documents retrieved' });
      }
    });
  });

app.use('/api', routes);
};

We can now get the data from our database by sending an HTTP request to this endpoint. A few key things, though:

  1. Limit does exactly what it looks like. I'm only getting 5 documents back.
  2. Lean strips away some stuff from the raw BSON, reducing complexity and overhead. Not required. But useful.
  3. When using find instead of findOne, confirm that the doc.length is greater than 0. This is because find always returns an array, so an empty array will not handle your error unless it is checked for length
  4. I personally like to send the error message in that format. Change it to suit your needs. Same thing for the returned document.
  5. The code in this example is written under the assumption that you have placed it in another file and not directly on the express server. To call this in the server, include these lines in your server code:
const app = express();
require('./path/to/this/file')(app) //