2011-04-29 30 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