javascriptmongodbmeteorpublishmeteor-publications

Linking users by id in Meteor publish


I've got a mongo document with the following format:

Group: {
    participants: [
        userId,
        userId,
        userId
    ]
}

...where the userIds are obviously Meteor's own ObjectIds for the users doc.

The issue I'm really having is that I want users to view other user info in their group. In this implementation I'm imagining a secure (read: I removed autopublish and insecure) group-messaging system.

My current publish implementation looks like this:

//grab all groups user belongs to
Meteor.publish("groups", function() {
    var groups = Groups.find({
        participants: {
            $in: [ this.userId ]
        }
    });
    return groups;
});

Now, ideally, I would love to just implement some code to manipulate groups before I finish publishing it to also publish each participant's user.profile data as well. The final format imagined would be as follows:

Group: {
    participants: {
        userId
    },
    users: {
        {   //One of these for each user
            userId,
            firstName,
            lastName,
            otherData
        }
    }
}

One thing I've noticed is that without autopublish and insecure, I can't just do this on the client through a helper function.


Solution

  • This is a fairly straightforward use case for the reywood:publish-composite package:

    Meteor.publishComposite('groups', {
        find: function() {
            return Groups.find({ participants: { $in: this.userId }});
        },
        children: [
            {
                find: function(group) {
                    return Meteor.users.find(
                        { _id: { $in: group.participants },
                        { fields: { firstName: 1, lastName: 1, otherData: 1 }});
                }
            },
        ]
    });
    

    Note that the users' _id field is always included, you don't need to explicitly call it out in the fields: list.