I'm trying to figure out how to sort my results by most recent to previous entries in MongoDb.
I'm using Node.JS and Express for my API and have the following end point:
router.route('/getbyowner/:ownerId')
.get(function(req, res) {
Alerts.find({ owner_id: req.params.ownerId }, function(err, alerts) {
if (err)
res.send(err);
res.json(alerts);
})
});
In the Mongoose docs I can see how you would sort based on a filed and apply asc or desc, like so:
// sort by "field" ascending and "test" descending
query.sort({ field: 'asc', test: -1 });
But the object array returned doesn't have an index field I can sort on.
How is sorting in asc / desc done if not on a specific field?
I tried the following and this did not work:
router.route('/getbyowner/:ownerId')
.get(function(req, res) {
Alerts.find.sort({ _id: -1 , owner_id: req.params.ownerId }, function(err, alerts) {
if (err)
res.send(err);
res.json(alerts);
})
});