Querying your Mongo Database

suggest change

A simple GET request. Assume the model lives in ./db/models/Article.js. Mongoose 7 queries are thenables: exec() does not take a callback. The callback form below is Mongoose 6 and earlier.

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 (err) {
        res.status(500).send({ success: false, message: err.message });
        return;
      }
      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(5) returns at most five documents.
  2. lean() returns plain objects instead of Mongoose documents. It is optional.
  3. find gives the callback an array. An empty array is not an error, so check doc.length. Check err first: on failure doc may be undefined.
  4. The JSON shape is only an example. Change it to suit the API.
  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) //

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents