Help! Publishing array of fields based on use profile


I would like to seek help on how to publish an array fields based on user profile.

Here’s the user profile:

"profile" : {
        "name" : "username",
        "company" : "qckPxDw5tc8zyMKMJ",
        "branch" : "yeTtBM955A7fbKpDt",
        "products" : [ 

here’s my publish function:

Meteor.publish( "products", function ( limit ) {
  var user = Meteor.users.findOne( {
    "_id": this.userId
  }, {
    fields: {
      profile: 1
  } );
  var profile = user.profile.products;
  var admin = Roles.userHasRole( this.userId, 'admin' );
  if ( admin ) {
    return Products.find();
  } else if ( limit ) {
    console.log( 'User Products:', profile );
    return Products.find( profile[ 0 ] );
  } else {
    return Products.find( profile[ 0 ], {
      limit: limit
    } );
} );

the above publication is working but only for index 0.

What I want is to publish all the products inside users profile.

I’ve tried this approach but I have a cursor error

return Products.find( profile );

i get this error:

Error: Mongo selector can\'t be an array.

What is the best approach on this matter?

I’m thinking you probably want

return Products.find({_id: {$in: profile}});

Also, just an FYI regarding your publication’s structure. As it stands, although it will re-run if the user id changes, it will not re-run if a user’s admin status changes during the life of the publication. See this guide section for more information.

It may also be worth considering imposing a hard limit on limit if the returned data could ever become “too much” (whatever your definition of that may be :wink:).

Thanks a lot @robfallows for this! :+1:

I’ve overlooked the $in operator!

It worked!! Don’t worry the profile of the user is not editable by non-admin, only the admin can edit the profile. On imposing a hard limit, yeah, maybe limit to only 3 products per user, as the products will not grow exponentially and it’s very minimal.

Thanks again! :grinning:

1 Like