Reputation: 1892
How could I display to my logged in user a list of posts from people they are following?
I have a post schema (cut down for simplicity):
const postSchema = {
userId: String,
description: String,
timestamp: Date,
longitude: Number,
latitude: Number,
}
And my follower schema (cut down also):
const followerSchema = {
userId: String, // person who click follow on a user
followingId: String, // the account they were viewing
timestamp: Date
}
How can I find the lastest posts where post.user
is equal to follower.followingId
(assuming that follower.userId
is equal to my logged in user as well)?.
Attempts so far:
I've spent a couple of hours on this and I can pull the results for just posts and then filter them down in Node.js, but this isn't efficient on a mass scale.
Here is a lookup query that isn't working:
const posts = await Post.aggregate([
{
$lookup:
{
from: "follower",
localField: "userId",
foreignField: "followingId",
as: "relationship"
}
},
{ "$match": { "relationship.userId": req.userId } }
]);
res.send({posts});
Any suggestions on how to get this working?
It may be a better solution for me to:
userId
equals any of the userIds in the array.Upvotes: 3
Views: 1006
Reputation: 1892
From technophyle's answer, I updated from: "follower"
to be from: "followers"
.
I also needed to access the first value of the array in the $match rather than the root (needed to add 0
).
{ "$match": { "relationship.0.userId": req.userId} }
const posts = await Post.aggregate([
{
$lookup:
{
from: "followers",
localField: "userId",
foreignField: "following",
as: "relationship"
}
},
{ "$match": { "relationship.0.userId": req.userId} }
]);
res.send({posts});
Upvotes: 0
Reputation: 9149
Try this:
const followings = await Follower.find({ userId: req.userId });
const followingIds = followings.map(f => f.followingId);
const posts = await Post.find({ userId: { $in: followingIds } });
BTW, using aggregate
query is a better solution. Try changing this:
$lookup:
{
from: "follower",
localField: "userId",
foreignField: "following",
as: "relationship"
}
to:
$lookup:
{
from: "followers",
localField: "userId",
foreignField: "followingId",
as: "relationship"
}
Upvotes: 3