猫鼬:按ID排序 [英] mongoose: Sorting by id

查看:54
本文介绍了猫鼬:按ID排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mongo db会在文档更新时对文档重新排序.我很希望这种情况发生,所以我发现使用_id的order将以一致的顺序返回文档.但是现在我无法排序.以下是我的查找查询,该查询查找由特定用户创建的帖子,并且我尝试按_id进行排序. 代码:

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. But now I am not able to sort. Below is my find query which finds posts created by a particular user and I am trying to sort by _id. 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);


})

});

推荐答案

第二个参数用于选择字段.您需要在第三个参数中添加选项:

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);
});

或者,您可以使用sort()函数:

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.

这篇关于猫鼬:按ID排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆