为什么分页插件和 skip/limit 在那个 mongodb 查询中不起作用?
Why paginate plugin and skip/limit don't work in that mongodb query?
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);
});
});
其中 post 我要分页的对象数组。
我检查了这个插件是否正常工作。当我使用 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
}
您可以使用 $slice
像这样对数组进行分页(使用 async/await)
let result = await myModel.find({mail: 'user2@example.com'}, {posts: {$slice: [0, 3]}})
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);
});
});
其中 post 我要分页的对象数组。 我检查了这个插件是否正常工作。当我使用 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
}
您可以使用 $slice
像这样对数组进行分页(使用 async/await)
let result = await myModel.find({mail: 'user2@example.com'}, {posts: {$slice: [0, 3]}})