如何限制退回的商品数量?

时间:2011-04-29 09:46:05

标签: mongoose

myModel.find({}, function(err, items){
console.log(items.length);    // big number
});

如何将退回的项目限制为仅插入最新的10个项目?

7 个答案:

答案 0 :(得分:159)

在最新的mongoose中(写作时为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
});

答案 1 :(得分:18)

像这样,使用.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 :(得分:7)

我有点懒,所以我喜欢简单的东西:

let users = await Users.find({}, null,{limit: 50});

答案 3 :(得分:4)

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

答案 4 :(得分:1)

出于某种原因,我无法使用提议的答案,但我找到另一种变体,使用select,对我有用:

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

api可能已经改变了吗?我使用的是3.8.19版本

答案 5 :(得分:1)

...另外请务必使用:

mongoose.Promise = Promise;

这将mongoose承诺设置为本机ES6承诺。没有这个补充,我得到了:

  

弃用警告:不推荐使用Mongoose:mpromise(mongoose的默认承诺库),而是插入您自己的承诺库:http://mongoosejs.com/docs/promises.html

答案 6 :(得分:0)

查找参数

参数查找功能需要如下:

  1. 条件«Object»
  2. [投影] «Object|String»个可选字段返回,请参见Query.prototype.select()
  3. [选项] «Object»可选,请参见Query.prototype.setOptions()
  4. [回调] «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
  }
);

其他信息

猫鼬允许您以不同的方式查询集合,例如: Official Documentation

// 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) {});
相关问题