Querying your Mongo Database
suggest changeA 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:
limit(5)returns at most five documents.lean()returns plain objects instead of Mongoose documents. It is optional.findgives the callback an array. An empty array is not an error, so checkdoc.length. Checkerrfirst: on failuredocmay be undefined.- The JSON shape is only an example. Change it to suit the API.
- 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) //
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents