Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

node.js - How do i use MongoDB aggregation match for an array to use pagination

I have two collections, User and Post. The User collection looks something like this:

{
 "_id": "ObjectID(...)",
 "name": "...",
 "gender": "...",
 "followers": [ObjectID(...), ObjectID(...), ObjectID(...), ....],
 "following": [ObjectID(...), ObjectID(...), ObjectID(...), ....]
}

where the followers and following fields are arrays of users.

And the Post collection looks something like this:

{
 "_id": "ObjectID(...)",
 "text": "...",
 "date": "...",
 "user": "ObjectID(...)"
}

where the user field represents which user is the owner of the post.

Now to get all the posts of user's following list, i.e. get all the posts of a user who he is currently following I am doing this:

const user = req.user;

let posts = [];
let aggs = [];

for (let follow of user.following) {
  aggs.push(
    Post.aggregate([
      {
        $match: { user: follow.user }, //the follow.user contains the _id of the owner user
      },
    ])
  );
}

for (let agg of aggs) {
  for await (let post of agg) {
    posts.push(post);
  }
}

res.send(posts);

where the req.user is a particular user. I know this is probably not a good solution but I don't know how do I pass an array of users to the $match option in aggregate.

This gets the job done so far. However, this returns all the posts. But if I want to do a pagination like we do in normal find() where we add a limit and skip option, I cannot do that here, because the $match operator would work on individual users' posts.

What i want is to get the cursor or pointer of all the posts and then do pagination, i.e returns the first 5 post. How do i accomplish this using mongoose queries?

I am using express v4.17.1 and mongoose v5.9.1.

Lastly, my apologies if I haven't been able to explain the question, or what I want accurately since English is not my first language. Any help is appreciated. Thanks!


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

1 Reply

0 votes
by (71.8m points)

you can pass a value for skip and limit for pagination its work for me

db.getCollection('user').aggregate([
   { $match: { "_id": "enter user id" } },
   { $lookup: {         
         from: "post",
         localField: "following",
         foreignField: "user",
         as: "my_docs" } 
    }, 
    { $unwind: '$my_docs' },
    {$project: {"my_docs" : 1}},
    {$skip: 0 },
    {$limit: 10}
])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...