我正在用Node.js和mongoose写一个web应用程序。如何对我从.find()调用得到的结果进行分页?我想要一个功能可比的“限制50,100”在SQL。


当前回答

使用这个简单的插件。

https://github.com/WebGangster/mongoose-paginate-v2

安装

NPM安装mongoose- pagate -v2 使用 添加插件到一个模式,然后使用模型paginate方法:

Const mongoose = require('mongoose'); const mongoosePaginate = require(' mongoosePaginate -v2'); const mySchema =新的猫鼬。模式({ /*你的模式定义*/ }); mySchema.plugin (mongoosePaginate); const myModel =猫鼬。模型(SampleModel, mySchema); myModel.paginate().then({}) //使用方法

其他回答

你可以使用一个叫Mongoose Paginate的小包,让它更容易。

$ npm install mongoose-paginate

在你的路由或控制器后,只需添加:

/**
 * querying for `all` {} items in `MyModel`
 * paginating by second page, 10 items per page (10 results, page 2)
 **/

MyModel.paginate({}, 2, 10, function(error, pageCount, paginatedResults) {
  if (error) {
    console.error(error);
  } else {
    console.log('Pages:', pageCount);
    console.log(paginatedResults);
  }
}

以上回答是正确的。

只是一个插件,任何人谁是异步等待而不是 承诺! !

const findAllFoo = async (req, resp, next) => {
    const pageSize = 10;
    const currentPage = 1;

    try {
        const foos = await FooModel.find() // find all documents
            .skip(pageSize * (currentPage - 1)) // we will not retrieve all records, but will skip first 'n' records
            .limit(pageSize); // will limit/restrict the number of records to display

        const numberOfFoos = await FooModel.countDocuments(); // count the number of records for that model

        resp.setHeader('max-records', numberOfFoos);
        resp.status(200).json(foos);

    } catch (err) {
        resp.status(500).json({
            message: err
        });
    }
};
const page = req.query.page * 1 || 1;
const limit = req.query.limit * 1 || 1000;
const skip = (page - 1) * limit;

query = query.skip(skip).limit(limit);

简单而强大的分页解决方案

async getNextDocs(no_of_docs_required: number = 5, last_doc_id?: string) {
    let docs

    if (!last_doc_id) {
        // get first 5 docs
        docs = await MySchema.find().sort({ _id: -1 }).limit(no_of_docs_required)
    }
    else {
        // get next 5 docs according to that last document id
        docs = await MySchema.find({_id: {$lt: last_doc_id}})
                                    .sort({ _id: -1 }).limit(no_of_docs_required)
    }
    return docs
}

Last_doc_id:您获得的最后一个文档id

No_of_docs_required:你想要获取的文档数量,例如5、10、50等。

如果你不提供last_doc_id给方法,你会得到5个最新的文档 如果你提供了last_doc_id,那么你会得到下一个,即5个文档。

这是一个你可以尝试的例子,

var _pageNumber = 2,
  _pageSize = 50;

Student.count({},function(err,count){
  Student.find({}, null, {
    sort: {
      Name: 1
    }
  }).skip(_pageNumber > 0 ? ((_pageNumber - 1) * _pageSize) : 0).limit(_pageSize).exec(function(err, docs) {
    if (err)
      res.json(err);
    else
      res.json({
        "TotalCount": count,
        "_Array": docs
      });
  });
 });