How do I limit the number of returned items?

前端 未结 7 2012
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 15:32
myModel.find({}, function(err, items) {
    console.log(items.length);    // Big number
});

How can I limit the returned items to only the latest

7条回答
  •  广开言路
    2020-11-27 16:15

    Find parameters

    The parameters find function takes are as follows:

    1. conditions «Object».
    2. [projection] «Object|String» optional fields to return, see Query.prototype.select()
    3. [options] «Object» optional see Query.prototype.setOptions()
    4. [callback] «Function»

    How to limit

    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
      }
    );
    

    Extra Info

    Mongoose allows you to query your collections in different ways like: 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) {});
    

提交回复
热议问题