Vlael
Vlael

Reputation: 32

Mongoose, how do I sort this by id and descending?

I have this code: and i want it to sort the musics through id and list it by desc so every time a user post the latest post is on the top.

router.get('/getAllMusic', (req, res) => {
    Music.find({}, (err, musics) => {
        if (err) {
            res.json({ success: false, message: err });
        }

        else if (!musics) {
            res.json({ success: false, message: musics});
        }

        else {
            res.json({ success: true, musics: musics});
        }
    }).sort({ '_id': -1 });
});

Upvotes: 0

Views: 86

Answers (1)

Rahul Sharma
Rahul Sharma

Reputation: 10081

If you have the date field in recode use that for sorting,

Because _id will not return the expected result. It does not sort only by timestamp, It's a combination of multiple parameters. Refer this

The 12-byte ObjectId value consists of:

a 4-byte value representing the seconds since the Unix epoch(timestamp),

a 3-byte machine identifier,

a 2-byte process id, and

a 3-byte counter, starting with a random value.

Upvotes: 1

Related Questions