Querying your Mongo Database
suggest changeA 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:
- Limit does exactly what it looks like. I’m only getting 5 documents back.
- Lean strips away some stuff from the raw BSON, reducing complexity and overhead. Not required. But useful.
- When using
find
instead offindOne
, confirm that thedoc.length
is greater than 0. This is becausefind
always returns an array, so an empty array will not handle your error unless it is checked for length - I personally like to send the error message in that format. Change it to suit your needs. Same thing for the returned document.
- 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