Meteor-Community-Packages / meteor-collection-hooks

Meteor Collection Hooks
https://atmospherejs.com/matb33/collection-hooks
MIT License
658 stars 90 forks source link

rewrite whole selector #237

Closed tillk9 closed 6 years ago

tillk9 commented 6 years ago

Isn't possible to rewrite the whole selector in .before.find ?

api.before.find(function (userId, selector) {
  selector =
  {
    $or:[
      {
        ... selector,
        userGroupId : "USER_GROUP_ID",
      },
      {public:true}
    ]
  }
  console.log("before",selector);
})

api.after.find(function(userId, selector, options, cursor){
  console.log("after",selector);
})

logs: bildschirmfoto vom 2018-02-07 16-34-58

I was expecting that the first and the second console.log() would display the same.

kmbriedis commented 6 years ago

A little late to respond but...

JavaScript parameters don't work that way, you cannot reassign them. See this https://stackoverflow.com/a/16880456

To accomplish the desired result, you can use an ugly workaround like this, you can see that the selector variable remains constant:

Chatrooms.before.find(function (userId, selector) {
  let newSelector =
  {
    $or:[
      {
        ... selector,
        userGroupId : "USER_GROUP_ID",
      },
      {public:true}
    ]
  }

  // Delete all existing keys
  for (let key in selector) {
    if (selector.hasOwnProperty(key)){
        delete selector[key];
    }
  }

  // Copy all fields to the object
  for (let key in newSelector) {
    if (newSelector.hasOwnProperty(key)){
        selector[key] = newSelector[key];
    }
  }

  console.log("before",selector);
})

logs: image

tillk9 commented 6 years ago

Thanky you! Your ugly workaround is much less ugly than mine and still useful to me. :)