【问题标题】:mongoose: Sorting by idmongoose:按 id 排序
【发布时间】:2014-06-26 17:51:47
【问题描述】:

mongo db 在文档更新时重新排序文档。我不希望这种情况发生,所以我发现使用 order by _id 会以一致的顺序返回文档。但现在我无法排序。下面是我的查找查询,它查找由特定用户创建的帖子,我正在尝试按 _id 排序。 代码:

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


})

});

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    第二个参数用于选择字段。第三个参数需要添加选项:

    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() 函数:

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

    您可以在documentation 中找到更多示例。

    【讨论】:

      猜你喜欢
      • 2015-09-19
      • 2012-07-21
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2018-10-05
      • 2014-04-01
      • 2016-01-08
      • 2019-10-19
      相关资源
      最近更新 更多