6

我正在使用 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函数,但是虽然我知道如何在常规集合中使用它们,但我必须知道如何将它们应用于子文档。有什么想法吗?

4

1 回答 1

0

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

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');
    }
}
于 2021-09-19T09:28:07.507 回答