Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

mongodb - Mongoose query with pagination not working properly

Mongo Version - v3.4 based on my last question - lookup with condition in mongoose

My query working on for page 1. but on the second page it gives empty result.

const casestudies = await CaseStudy.aggregate([{
                $lookup: {
                    from: "categories",
                    localField: "category_id",
                    foreignField: "_id",
                    as: "category_id"
                }
            },
            {
                $project: {
                    "updated_at": 0,
                    "category_id.updated_at": 0
                }
            },
            {
                $lookup: {
                    from: "bookmarks",
                    localField: "_id",
                    foreignField: "type",
                    as: "bookmarks"
                }
            },
            {
                $addFields: {
                    bookmarks: {
                        $filter: {
                            input: "$bookmarks",
                            cond: { $eq: ["$$this.user_id", req.user ? objectId(req.user._id) : ''] }
                        }
                    }
                }
            },
            { $sort: { "publish_date": -1 } },
            { $limit: pageSize },
            { $skip: (page - 1) * pageSize }
        ]);

What's wrong in my query. Please help me.

question from:https://stackoverflow.com/questions/65558282/mongoose-query-with-pagination-not-working-properly

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

so as suggested by @Ashh issue in order of sort,$skip, $limit. so the correct query should be.

{ $sort: { "publish_date": -1 } },
{ $skip: (page - 1) * pageSize },
{ $limit: pageSize }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...