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

如何将退回的商品限制为仅插入的最新 10 件商品?

4

7 回答 7

221

在最新的 mongoose(撰写本文时为 3.8.1)中,您做了两件不同的事情:(1)您必须将单个参数传递给 sort(),它必须是一组约束或只有一个约束,以及(2 ) execFind() 消失了,取而代之的是 exec()。因此,使用 mongoose 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
  });
于 2013-12-15T14:43:53.877 回答
27

像这样,使用 .limit():

var q = models.Post.find({published: true}).sort('date', -1).limit(20);
q.execFind(function(err, posts) {
  // `posts` will be of length 20
});
于 2011-04-29T13:58:28.193 回答
23

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

let users = await Users.find({}, null, {limit: 50});
于 2018-12-21T22:08:11.020 回答
9
models.Post.find({published: true}, {sort: {'date': -1}, limit: 20}, function(err, posts) {
 // `posts` with sorted length of 20
});
于 2017-02-07T10:07:06.740 回答
6

查找参数

find函数的参数如下:

  1. 条件«Object»
  2. [projection]«Object|String»要返回的可选字段,请参见Query.prototype.select()
  3. [options]«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
  }
);

额外信息

Mongoose 允许您以不同的方式查询您的集合,例如: 官方文档

// 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) {});
于 2019-04-30T05:48:11.883 回答
2

出于某种原因,我无法将其与建议的答案一起使用,但我发现了另一种使用 select 的变体,它对我有用:

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

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

于 2014-12-07T06:47:10.970 回答
2

...另外确保使用:

mongoose.Promise = Promise;

这将 mongoose 承诺设置为原生 ES6 承诺。没有这个添加我得到:

DeprecationWarning: Mongoose: mpromise (mongoose 的默认承诺库) 已被弃用,请插入您自己的承诺库:http ://mongoosejs.com/docs/promises.html

于 2017-09-01T17:15:33.287 回答