首页 > 解决方案 > 为什么分页插件和跳过/限制在那个 mongodb 查询中不起作用?

问题描述

const paginateScheme = new Schema({

        posts: [ { img: String, description: String, liked: String, postComId: String, comments: [ { author: String, text: String } ] } ],
    }, {collection: "usersData"});

paginateScheme.plugin(mongoosePaginate);
const myModel  = mongoose.model("sample", paginateScheme);


app.put("/api/pagination", function(req, res){

    const options = {
        page: 1,
        limit: 3,
        collation: {
            locale: 'en',
        },
    };

    const query = User.find({mail: 'user2@example.com'}, {posts: 1 });


    myModel.paginate(  query , options, function (err, result) {
        if(err) return console.log(err);
        res.send(result);
    });
});

在哪里发布我要分页的对象数组。我检查了这个插件工作正常。当我使用 Model.find({}) 它通过外部对象分页没有任何问题。我尝试使用skip + limit,但它什么也没返回。

this query returns:
{
  docs: [ { _id: 601a8f013d86dc237468467c, posts: [Array] } ],
  totalDocs: 1,
  limit: 3,
  totalPages: 1,
  page: 1,
  pagingCounter: 1,
  hasPrevPage: false,
  hasNextPage: false,
  prevPage: null,
  nextPage: null
}

标签: mongodbmongoosepaginationmongodb-querymongoose-schema

解决方案


你可以使用$slice这样的数组分页(使用异步/等待)

let result = await myModel.find({mail: 'user2@example.com'}, {posts: {$slice: [0, 3]}})

推荐阅读