Answers:
在最新的猫鼬(撰写本文时为3.8.1)中,您做了两件事不同:(1)您必须将单个参数传递给sort(),该参数必须是约束数组或仅一个约束,以及(2 )execFind()消失了,取而代之的是exec()。因此,使用猫鼬3.8.1可以做到这一点:
var q = models.Post.find({published: true}).sort({'date': -1}).limit(20);
q.exec(function(err, posts) {
// `posts` will be of length 20
});
或者您可以像这样简单地将其链接在一起:
models.Post
.find({published: true})
.sort({'date': -1})
.limit(20)
.exec(function(err, posts) {
// `posts` will be of length 20
});
像这样,使用.limit():
var q = models.Post.find({published: true}).sort('date', -1).limit(20);
q.execFind(function(err, posts) {
// `posts` will be of length 20
});
models.Post.find({published: true}, {sort: {'date': -1}, limit: 20}, function(err, posts) {
// `posts` with sorted length of 20
});
查找参数
参数查找功能需要如下:
«Object»
。«Object|String»
要返回的可选字段,请参见Query.prototype.select()«Object»
可选,请参见Query.prototype.setOptions()«Function»
如何限制
const Post = require('./models/Post');
Post.find(
{ published: true },
null,
{ sort: { 'date': 'asc' }, limit: 20 },
function(error, posts) {
if (error) return `${error} while finding from post collection`;
return posts; // posts with sorted length of 20
}
);
额外信息
猫鼬允许您以多种方式查询收藏,例如: 官方文档
// named john and at least 18
MyModel.find({ name: 'john', age: { $gte: 18 }});
// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
// executes, name LIKE john and only selecting the "name" and "friends" fields
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })
// passing options
MyModel.find({ name: /john/i }, null, { skip: 10 })
// passing options and executes
MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});
// executing a query explicitly
var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
query.exec(function (err, docs) {});
// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});