0

I want to be able to sore a json object array not by a field, but by the most recent post to later post, or I believe it would be ascending order.

My typical approach would be by comparing a field like first or last name with the following:

someArray.sort(function(a, b){
    if ( a.someField < b.someField )
        return -1;
    if ( a.someField > b.someField )
        return 1;
    return 0;
});

The data set returned is form my api, which returns a json object array from MongoDb.

Thanks for any advice!!

Sample of dataset returned:

[
    {
        "_id": "5a787d79e2676c6711cfaf99",
        "owner_id": "5a787bacae6d9926d313051e",
        "__v": 0,
        "first_name": "Sarah",
        "last_name": "Paul",
        "initial": "",
        "accepted": true,
    },
    {
        "_id": "5a787d79e2676c6788cfaf99",
        "owner_id": "5a787bacae6d9926d313051e",
        "__v": 0,
        "first_name": "Jim",
        "last_name": "Albertson",
        "initial": "B",
        "accepted": true,
    },
    {
        "_id": "5a787d79e2676c6711cfa089",
        "owner_id": "5a787bacae6d9926d313051e",
        "__v": 0,
        "first_name": "Corry",
        "last_name": "Rich",
        "initial": "",
        "accepted": false,
    },
]

Sample of code in my API that returns dataset:

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);
        })
    });
cnak2
  • 1,711
  • 3
  • 28
  • 53

1 Answers1

0

Check out this answer: https://stackoverflow.com/a/22226514/4125622 I think what you need to do is

Alerts.find({ owner_id: req.params.ownerId }).sort({ $natural: -1 }).limit(YOUR_LIMIT_OF_RESULTS)
Phil
  • 7,065
  • 8
  • 49
  • 91
  • Thanks, Phil. I'm fairly new to Mongo. I added my express API function to the original post. How would I configure it to impliment what you are suggesting? – cnak2 Apr 30 '18 at 13:15
  • I edited my answer, take a look at that other SO-thread, maybe it helps – Phil Apr 30 '18 at 13:26
  • Thanks, Phil. I'm trying to see how I work what you have into my code to test, but I think I'm missing the right formatting. I'll let you know if I figure it out. Thanks for the help!! – cnak2 Apr 30 '18 at 13:52