Luke Brown
Luke Brown

Reputation: 1892

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.

Upvotes: 3

Views: 1006

Answers (3)

Luke Brown
Luke Brown

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

technophyle
technophyle

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

Sylvain
Sylvain

Reputation: 529

I think that the foreignField should be ”followingId”.

Upvotes: 0

Related Questions