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:
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 lengthconst app = express();
require('./path/to/this/file')(app) //