mongoose:按idsorting

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

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

第二个参数是要select的字段。 您需要将选项添加到第三个参数:

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

你可以在文档中find更多的例子。