Meteor-Community-Packages / meteor-collection-hooks

Meteor Collection Hooks

Home Page:https://atmospherejs.com/matb33/collection-hooks

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

rewrite whole selector

tillk9 opened this issue · comments

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.

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

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