Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB search feed based on if I'm following users

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:

  1. 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.

  2. 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?

  1. It may be a better solution for me to:

    • Load all users that I follower, and get their IDs
    • Load all posts where userId equals any of the userIds in the array.
like image 323
Luke Brown Avatar asked Nov 23 '25 04:11

Luke Brown


1 Answers

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"
        }
like image 162
technophyle Avatar answered Nov 25 '25 17:11

technophyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!