myModel.find({}, function(err, items){
console.log(items.length); // big number
});
如何将返回的项目限制为仅插入最新的10个项目?如何限制退货数量?
myModel.find({}, function(err, items){
console.log(items.length); // big number
});
如何将返回的项目限制为仅插入最新的10个项目?如何限制退货数量?
在最新的猫鼬(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
});
,或者你可以简单地这样在一起IT连锁:
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().sort('-date').limit(10).select('published').exec(function(e, data){
...
});
已在API也许改变了吗?我使用的版本,19年3月8日
models.Post.find({published: true},{date: 1}, {sort{'date': -1}, limit: 20}, function(err, posts) {
// `posts` with sorted length of 20
});
尽管这段代码可能会解决这个问题,包括对* how *和* why的解释,这就解决了这个问题[真的有帮助](// meta.stackexchange.com/q/114762)来提高你的文章的质量。请记住,你正在为将来的读者回答这个问题,而不仅仅是现在问的人!请编辑您的答案以添加解释,并指出适用的限制和假设。 – 2017-02-07 11:42:35
...另外一定要使用:
mongoose.Promise = Promise;
这将猫鼬承诺本地ES6承诺。如果没有这除了我:
DeprecationWarning:猫鼬:mpromise(猫鼬的默认承诺库)已被弃用,插上自己的诺言库,而不是:http://mongoosejs.com/docs/promises.html
{'date':-1}是什么意思?提前致谢! – kurumkan 2016-10-31 11:55:23
@ArslArsl - 结果将按降序排列。 – 2016-11-02 15:10:33