我没有找到排序修饰符的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]);
当前回答
Post.find().sort({updatedAt: 1});
其他回答
其他人为我工作,但这个做到了:
Tag.find().sort('name', 1).run(onComplete);
解决方案:
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().sort({updatedAt: 1});
自2020年10月起,为了解决您的问题,您应该将.exec()添加到调用中。不要忘记,如果你想在调用之外使用这些数据,你应该在异步函数内部运行类似这样的东西。
let post = await callQuery();
async function callQuery() {
return Post.find().sort(['updatedAt', 1].exec();
}