如何与mongoose分页

我想在我的collections中做一个分页function。 如何查找带有“开始”和“限制”位置的文档,并在单个查询中获取总文档编号?

你不能在一个查询中得到两个结果。 你可以做的最好的办法是让它们都使用一个Mongoose Query对象:

 var query = MyModel.find({}); query.count(function(err, count) {...}); query.skip(5).limit(10).exec('find', function(err, items) {...}); 

如果需要的话,使用像async这样的stream程控制框架来并行执行它们。

您可以使用Mongoose Paginate插件:

 $ npm install mongoose-paginate 

在您的路线或控制器后,只需添加:

 Model.paginate({}, { page: 3, limit: 10 }, function(err, result) { // result.docs // result.total // result.limit - 10 // result.page - 3 // result.pages }); 

如果你打算有很多页面,你不应该使用跳过/限制,而是计算范围。

看到斯科特的回答类似的问题: MongoDB – 分页

更新:

使用跳过和限制不适合分页。 这是关于它的讨论。

韦弗曼,给出了很好的答案。 我读链接的姿势,你应该使用范围查询。 n = 0; i = n + 10; db.students.find({“id”:{$ gt:n,$ lt:(n + i)}});

老解答 (不要用这个)

使用类似的东西

 n = db.students.find().skip(n).limit(10); //pass n dynamically, so for page 1 it should be 0 , page 2 it should be 10 etc 

更多文档在http://www.mongodb.org/display/DOCS/Advanced+Queries

  user.find({_id:{$nin:friends_id},_id:{$ne:userId}},function(err,user_details){ if (err) res.send(err); response ={ statusCode:200, status:true, values:user_details } res.json(response); }).skip(10).limit(1);