Publish only certain fields in if statement

I have a publish function where I’m checking to see if the user’s role is Admin or not.

If so, then I want to publish the whole collection, if not, I just want a couple of fields from the collection.

Meteor.publish("configSettings", function() {
    let isAdmin = Roles.userIsInRole(this.userId, 'Admin');

    if (isAdmin) {
        console.log("Is ADmin");
        return ConfigColl.find({});
    } else {
        console.log("Is Not Admin!!!");
        return ConfigColl.find({}, { _id: 0, maxNoOfSitesFree: 1, defaultFreq: 1 });
    }
});

I’m checking the subscription data with Meteor Toys, and i’m only seeing the full publish of data even though I can see that it recognizees my user is not an admin.

Am I misunderstanding how to do this?

1 Like

You just have a very simple issue that is very likely due to the signature of Meteor’s Collection.find() as opposed to MongoDB’s.

For MongoDB’s api you have Collection.find(selector, projection) with projection being an object who’s keys specify the fields you wish to retrieve, whereas with meteor the signature is Collection.find(selector, options) where options can have many different keys such as limit, skip and fields. In this case the fields key takes the place of the projection parameter.

The following change should fix things for ya

Meteor.publish("configSettings", function() {
    let isAdmin = Roles.userIsInRole(this.userId, 'Admin');

    if (isAdmin) {
        console.log("Is ADmin");
        return ConfigColl.find({});
    } else {
        console.log("Is Not Admin!!!");
        return ConfigColl.find({}, { 
            fields: {
                _id: 0,
                maxNoOfSitesFree: 1,
                defaultFreq: 1
            }
        });
    }
});
3 Likes