【问题标题】:How to return 25 results at a time with mongoose [duplicate]如何使用猫鼬一次返回 25 个结果 [重复]
【发布时间】:2016-07-30 23:48:38
【问题描述】:

我正在创建一个 RESTful API,它将返回 MongoDB 集合中的文档。由于是 RESTful,我想将返回的文档数量限制为 25,然后让客户端要求下一个 25,然后再下一个,依此类推,直到所有文档都被读取。使用 find() 我可以获取集合中的“所有”文档,使用 find().limit() 我可以将其限制为 25 个,但它总是会获得前 25 个。那里有什么好的代码示例展示如何记住您在 find() 中停止的位置,以便第二次调用 find 将返回集合中接下来的 25 个文档?到目前为止我的代码......

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {        
    Transaction.find(function (err, transactions) {
        if (err) {
            mongoose.connection.close();                
            res.send('FAIL');
        } else {
            mongoose.connection.close();
            res.send(transactions);
        }            
    }).limit(25);
});

发送!

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    使用skip:

    var recordsPerPage = 25;
    
    Transaction
        .find()
        .skip((currentPage - 1) * recordsPerPage)
        .limit(recordsPerPage)
        .exec(function (err, transactions) {
            res.send(transactions);
        });
    

    skip 将开始从您传入的位置参数返回结果。因此,如果您想要第 3 页的结果(结果 51 到 75),您只需跳过前 50 个结果。

    【讨论】:

      猜你喜欢
      • 2015-08-04
      • 1970-01-01
      • 2018-08-22
      • 2014-05-30
      • 2015-08-26
      • 1970-01-01
      • 2014-01-09
      • 2016-06-20
      相关资源
      最近更新 更多