Mongoose: Sort by ID

mongo db reorders documents when a document is updated. I want this to happen, so I found that using order with _id will return documents in sequential order. But now I can’t sort. Below is my search query, which finds messages created by a specific user, and I'm trying to sort by _id. The code:

app.get('/posts/:user_id',function(req,res){

posts.find({
    'creator.user_id':req.params.user_id
},[],{ sort: { '_id': -1 } },function(err,userpost){
    if(err)
        res.send(err);
    res.json(userpost);


})

});
+4
source share
1 answer

The second parameter is for selecting fields. You need to add parameters to the third parameter:

posts.find({'creator.user_id': req.params.user_id}, null, {sort: {'_id': -1}}, function(err,userpost) {
    if(err)
        res.send(err);
    res.json(userpost);
});

Alternatively, you can use the function sort():

posts.find({'creator.user_id': req.params.user_id}).sort({'_id': -1}).exec(function(err,userpost) {
    if(err)
        res.send(err);
    res.json(userpost);
});

.

+8

Source: https://habr.com/ru/post/1546177/


All Articles