Meteor Edition - Composite and Nested Collection

I am trying to create an application that has many different relationships in Meteor. There will be works, clients and user collections. Clients can have multiple jobs, and most importantly, multiple users can work on the same job.

I have a set of jobs configured as follows in my settings file:

Jobs.insert({
  jobNum: 'Somejob',
  clientId: 'XXXXXXXX',
  clientName: 'Some Client',
  rate: XX,
  userNames: [
    {userId: user1._id},
    {userId: user2._id}
  ],
  active: true
});

      

I am publishing according to the readme for publish-composite, but I cannot get users to publish to the client. Here is the posting code:

Meteor.publishComposite('jobsActive', {
  find: function() {
  // Find all active jobs any client
  return Jobs.find({active: true});
  },

  children: [
    {
     find: function (job) {
        // Return a client associated with the job
        return Clients.find({_id: job.clientId}); 
    }
    },
    {
     find: function (job) {
        // Return all users associated with the job
        // This is where the problem is
        return Meteor.users.find({_id: job.userNames.userId});
     }
   }
 ]
});

      

I cannot figure out how to find the array correctly. I tried several things and nothing worked. Is it possible? Or do I need to go about it differently? I was thinking about linking to jobs in the users collection, but there will be a lot more jobs than users, so it seems like it makes more sense.

By the way, I also subscribed to "jobsActive". The other two collections are client-side; I just can't post a collection of users.

Thanks for any help and ideas.

+3


source to share


2 answers


job.userNames.userId

does not exist in your collection. job.userNames

is an array of objects holding a key userId

.

Try something like _.map( job.userNames, function( users ){ return users.userId } )

.



Your code will be:

Meteor.publishComposite('jobsActive', {
    find: function() {
        return Jobs.find({active: true});
    },
    children: [
        {
            find: function (job) {
                return Clients.find({_id: job.clientId}); 
            }
        },
        {
            find: function (job) {
                return Meteor.users.find({ _id: { $in: _.map( job.userNames, function( users ) { return users.userId } ) } });
            }
        }
    ]
});

      

+2


source


I think you don't need publish-composite at all, try this code snippet. I like!



Meteor.publish('jobsActive', function () {
    return Events.find(
    {
        $or: [
            // { public: { $eq: true } },
            { active: true },
            { userNames: this.userId}
        ],
    },
    {
        sort: {createdAt: -1}
    }
    );
});

      

0


source







All Articles