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!