mongoose: Sorting by id

前端 未结 1 973
余生分开走
余生分开走 2021-01-18 05:08

mongo db reorders the documents when ever a document is updated. I dint want this to happen so I found that using order by _id would return the documents in consistent order

相关标签:
1条回答
  • 2021-01-18 05:29

    The second parameter is for the fields to select. You need to add options 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 sort() function:

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

    You can find more examples in the documentation.

    0 讨论(0)
提交回复
热议问题