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