2011-04-29 29 views

回答

121

在最新的猫鼬(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 
}); 
+0

{'date':-1}是什么意思?提前致谢! – kurumkan 2016-10-31 11:55:23

+1

@ArslArsl - 结果将按降序排列。 – 2016-11-02 15:10:33

17

与此类似,使用.limit():

var q = models.Post.find({published: true}).sort('date', -1).limit(20); 
q.execFind(function(err, posts) { 
    // `posts` will be of length 20 
}); 
+2

非常感谢,不知道你能使这样的查询。我在哪里可以找到关于此execFind方法的某种形式的文档? – 2011-04-29 14:18:54

+0

老实说,我只是看猫鼬来源和东西的例子,以及测试用例。邮件列表也很好。实际的文档看起来有点过时了。 – kcbanner 2011-04-29 14:25:09

+1

是execFind仍然在最新版本的mongoosejs? – Manny 2013-12-09 02:32:16

1

出于某种原因,我不能让这个与合作提出答案,但我发现了另一个变种,使用选择,这为我工作:

models.Post.find().sort('-date').limit(10).select('published').exec(function(e, data){ 
     ... 
}); 

已在API也许改变了吗?我使用的版本,19年3月8日

0
models.Post.find({published: true},{date: 1}, {sort{'date': -1}, limit: 20}, function(err, posts) { 
// `posts` with sorted length of 20 
}); 
+4

尽管这段代码可能会解决这个问题,包括对* how *和* why的解释,这就解决了这个问题[真的有帮助](// meta.stackexchange.com/q/114762)来提高你的文章的质量。请记住,你正在为将来的读者回答这个问题,而不仅仅是现在问的人!请编辑您的答案以添加解释,并指出适用的限制和假设。 – 2017-02-07 11:42:35

0

...另外一定要使用:

mongoose.Promise = Promise; 

这将猫鼬承诺本地ES6承诺。如果没有这除了我:

DeprecationWarning:猫鼬:mpromise(猫鼬的默认承诺库)已被弃用,插上自己的诺言库,而不是:http://mongoosejs.com/docs/promises.html