【发布时间】:2011-08-15 02:16:00
【问题描述】:
假设我在 Mongoose 中运行此查询:
Room.find({}, (err,docs) => {
}).sort({date:-1});
这行不通!
【问题讨论】:
假设我在 Mongoose 中运行此查询:
Room.find({}, (err,docs) => {
}).sort({date:-1});
这行不通!
【问题讨论】:
Mongoose 中的Sorting 已在版本中演变,因此其中一些答案不再有效。从 Mongoose 4.1.x 版本开始,可以通过以下任何一种方式对 date 字段进行降序排序:
Room.find({}).sort('-date').exec((err, docs) => { ... });
Room.find({}).sort({date: -1}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'desc'}).exec((err, docs) => { ... });
Room.find({}).sort({date: 'descending'}).exec((err, docs) => { ... });
Room.find({}).sort([['date', -1]]).exec((err, docs) => { ... });
Room.find({}, null, {sort: '-date'}, (err, docs) => { ... });
Room.find({}, null, {sort: {date: -1}}, (err, docs) => { ... });
对于升序排序,省略字符串版本上的- 前缀或使用1、asc 或ascending 的值。
【讨论】:
Query#find([criteria], [callback])。我想也许有一些秘密握手说“条件”最多可以包含三个参数,但它将类型列为“对象”。
find 方法。见Model.find。
Module#property 表示法并搜索#find。似乎没有简单的方法来导航或搜索文档。搜索 find 会产生 187 个结果。
_id 字段排序。例如,要获取最近的记录,您可以这样做:await db.collection.findOne().sort({ _id: -1 });
正确答案是:
Blah.find({}).sort({date: -1}).execFind(function(err,docs){
});
【讨论】:
今天一直在使用 Mongoose 3.5(.2) 处理这个问题,但没有一个答案能帮助我解决这个问题。下面的代码 sn -p 可以解决问题
Post.find().sort('-posted').find(function (err, posts) {
// user posts array
});
您可以将所需的任何标准参数发送到find()(例如 where 子句和返回字段),但 no 回调。如果没有回调,它会返回一个链接 sort() 的 Query 对象。您需要再次调用find()(有或没有更多参数——出于效率原因不应该需要任何参数),这将允许您在回调中获得结果集。
【讨论】:
Post.find().sort({date:-1}, function(err, posts){
});
应该也可以
编辑:
如果遇到错误sort() only takes 1 Argument,您也可以尝试使用它:
Post.find({}, {
'_id': 0, // select keys to return here
}, {sort: '-date'}, function(err, posts) {
// use it here
});
【讨论】:
Error: sort() only takes 1 Argument
Post.find({}, {'_id': 0}).sort("-date").function(err, posts){});
我这样做:
Data.find( { $query: { user: req.user }, $orderby: { dateAdded: -1 } } function ( results ) {
...
})
这将首先显示最近的内容。
【讨论】:
$orderby 在 MongoDB 3.2 中已弃用,因此不应再使用。
【讨论】:
短解:
const query = {}
const projection = {}
const options = { sort: { id: 1 }, limit: 2, skip: 10 }
Room.find(query, projection, options).exec(function(err, docs) { ... });
【讨论】:
这里的所有答案实际上都是正确的,但是我写我的答案是为了明确指出,如果你没有一个名为“日期”的字段,有时写 '-date' 或 date: -1 将不起作用在您的模型中,或者如果您在创建模型时在选项中传递了选项:时间戳:true。如果您使用的是 timestamps: true,那么您需要输入:sort({createdAt: -1}) 这样就可以了。
【讨论】:
这个对我有用。
`Post.find().sort({postedon: -1}).find(function (err, sortedposts){
if (err)
return res.status(500).send({ message: "No Posts." });
res.status(200).send({sortedposts : sortedposts});
});`
【讨论】:
使用 Koa 的 ES6 解决方案。
async recent() {
data = await ReadSchema.find({}, { sort: 'created_at' });
ctx.body = data;
}
【讨论】:
您还可以按_id 字段排序。例如,要获取最近的记录,您可以这样做,
const mostRecentRecord = await db.collection.findOne().sort({ _id: -1 });
它也快得多,因为我非常愿意打赌你的 date 字段没有被索引。
【讨论】: