我没有找到排序修饰符的doc。唯一的洞见在单元测试中: spec.lib.query.js # L12
writer.limit(5).sort(['test', 1]).group('name')
但这对我不起作用:
Post.find().sort(['updatedAt', 1]);
我没有找到排序修饰符的doc。唯一的洞见在单元测试中: spec.lib.query.js # L12
writer.limit(5).sort(['test', 1]).group('name')
但这对我不起作用:
Post.find().sort(['updatedAt', 1]);
当前回答
解决方案:
posts.find().sort({field:1})
//升序和降序使用-1而不是1
其他回答
还可以使用aggregate()进行排序
const sortBy = req.params.sort;
const limitNum = req.params.limit;
const posts = await Post.aggregate([
{ $unset: ['field-1', 'field-2', 'field-3', 'field-4'] },
{ $match: { field-1: value} },
{ $sort: { [sortBy]: -1 } }, //-------------------> sort the result
{ $limit: Number(limitNum) },
]);
您可以对查询结果进行排序
Post.find()。排序({createdAt:“降序”});
在Mongoose中,排序可以通过以下任何一种方式完成:
Post.find({}).sort('test').exec(function(err, docs) { ... });
Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
Post.find({}).sort({test: 1}).exec(function(err, docs) { ... });
Post.find({}, null, {sort: {date: 1}}, function(err, docs) { ... });
Post.find().sort({updatedAt:1}).exec(function (err, posts){
...
});
这是我如何得到排序工作在猫鼬2.3.0:)
// Find First 10 News Items
News.find({
deal_id:deal._id // Search Filters
},
['type','date_added'], // Columns to Return
{
skip:0, // Starting Row
limit:10, // Ending Row
sort:{
date_added: -1 //Sort by Date Added DESC
}
},
function(err,allNews){
socket.emit('news-load', allNews); // Do something with the array of 10 objects
})