Aero
Aero

Reputation: 317

Meteor: Publish using users profile properties rather than ID

I'm currently creating an app that will be used by multiple companies. Each user has the following profile:

username: johnDoe    
emails: [{address: "[email protected]", verified: true}],
profile: {
             name: "John Doe",
             companyId: "1234"
}

I then have a collection (called Companies) of company objects that contain configuration info, templates etc specific to that company.

{
    id: "1234",
    configuration: {},
    templates: []
}

In order to isolate each companies data I want to only publish data that matches the users profile companyId to the companies id.

if (Meteor.isServer) {
    // collection to store all customer accounts
    Companies = new Mongo.Collection('Companies');

    // publish collection
    Meteor.publish("Company", function () {
         return Companies.find({id: Meteor.user().profile.companyId});
    })
}

This currently works if I hardcode the clinic Id

    // publish collection
    Meteor.publish("Company", function () {
         return Companies.find({id: "1234");
    })

But returns an empty cursor with the Meteor.user().profile.companyId. This means that the issue is either that I'm using the wrong function or more probably, the publish is happening before the user().profile.companyId can run.

Anybody know what I'm doing wrong? and do you have any advice on what to read up about so that I have an understanding of this moving forwards?

Thanks

Upvotes: 0

Views: 43

Answers (1)

Stephen Woods
Stephen Woods

Reputation: 4049

Try doing an explicit findOne() in your publish function:

// publish collection
Meteor.publish("Company", function () {
     var user = Meteor.users.findOne({_id: this.userId});
     if(user && user.profile && user.profile.companyId) {
       return Companies.find({id: user.profile.companyId});
     } else {
       console.log(user);
       return this.ready();
     }
});

Upvotes: 1

Related Questions