0

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);
        })
    });
cnak2
  • 1,711
  • 3
  • 28
  • 53
  • Umm It's **Always** based on a field. You can sort on `_id` for what "should be" representative of insertion order as long as the values are the default `ObjectId` values that is. Otherwise you need to pick a key to order on that is more representative of "recent" to your perspective. `ObjectId` values are accurate to the "second" as a date representation, and for more "fine grained" results you would create an actual "date" value within your document. – Neil Lunn May 05 '18 at 02:14
  • Note also that `sort({ _id: -1 })`, `sort({ _id: 'desc' })` and `sort("-_id")` all essentially mean the same thing in their eventual translation. Which is actually always the first one, since that's what the server understands – Neil Lunn May 05 '18 at 02:16
  • Thanks, Neil, I added some code to my original post and I get an error saying error: "Alerts.find.sort is not a function". Any advice would be appreciated. I know I'm close... – cnak2 May 05 '18 at 17:03
  • Figured it out... Thanks for the help! – cnak2 May 05 '18 at 17:36

0 Answers0