gpt4 book ai didi

mongodb - Mongoose 中的子文档分页

转载 作者:行者123 更新时间:2023-12-04 12:04:08 24 4
gpt4 key购买 nike

我正在使用 Mongoose 3.6 并且我的(简化的)模式如下所示

var commentSchema = new Schema({
created: Date
});

var userSchema = new Schema({
comments : [commentSchema],
});

我想对评论进行分页,这样如果我有一个有 25 条评论的用户,页面将分为:
page 1: comments 15-24
page 2: comments 5-14
page 3: comments 0-4
page 4: empty
page 5: empty
...

这是我试过的
this.findById(user_id, {
comments: {
$slice: [-comment_page_index * comments_per_page, comments_per_page]
}
}, function(err, user) {
//...
});

虽然一开始似乎可行,但我很失望地发现 $slice运算符在到达集合边界时切断给定的索引。

所以我得到的是
page 1: comments 15-24
page 2: comments 5-14
page 3: comments 0-9
page 4: comments 0-9
page 5: comments 0-9
...

这里更好的选择可能是结合 sort , skiplimit函数,但虽然我知道如何在常规集合中使用它们,但我必须知道如何将它们应用于子文档。有什么想法吗?

最佳答案

如果找到全部或与显示相关,分页将类似于下面的代码。代码只是一个例子:

findAll: async function (req, res) {
var responseObj = {};
try {
var responseObj = {};
var queryArray = [];
var finalAnswer = [];

var loggedinUser = mongoose.Types.ObjectId(req.user.id)
var auser = await user.findOne({ _id: loggedinUser })
var places = auser.placesUnderIt;
for (i of places) {
var singlePlaceId = mongoose.Types.ObjectId(i);
var singlePlaceData = await place.findOne({ _id: singlePlaceId })
var list = singlePlaceData.controlledStore;
for (k of list) {
finalAnswer.push(k);
}

}
queryArray.push({ _id: { $in: finalAnswer} });
var query = {
$and: queryArray
}

responseObj.count = await store.countDocuments(query);
responseObj.data = await store.find(query)
.populate('ownerId', ["firstName", "lastName", "phoneNumber", "email", "personalDetails"])
.populate('businesses')
.limit(parseInt(req.query.limit))
.skip(parseInt(req.query.skip));

var data = responseObj.data;
return res.send(responseObj);
} catch (err) {
return res.send('Error');
}
}

关于mongodb - Mongoose 中的子文档分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16752917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com