如何使用猫鼬一次返回25个结果

lew*_*ada 2 mongoose mongodb node.js

我正在创建一个RESTful API,它将返回MongoDB集合中的文档.作为RESTful,我想将返回的文档数量限制为25,然后让客户端请求下一个25,然后是下一个,依此类推,直到所有文档都被读取为止.使用find()我可以在集合中获取'all'文档,并使用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);
});
Run Code Online (Sandbox Code Playgroud)

TX!

Kom*_*omo 6

用途skip:

var recordsPerPage = 25;

Transaction
    .find()
    .skip((currentPage - 1) * recordsPerPage)
    .limit(recordsPerPage)
    .exec(function (err, transactions) {
        res.send(transactions);
    });
Run Code Online (Sandbox Code Playgroud)

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