Is it possible to use a variable in a meteor collection update/removal?

半世苍凉 提交于 2019-12-20 06:29:10

问题


So I was thinking about refactoring my code in the following way.

Meteor.call("RemoveNotification", this._id, function(error, response){
}

and

Meteor.call("RemoveAvailablePlayer", this._id, function(error, response){
}

into

Meteor.call("RemoveFromDatabase", "Notifications", this_id, function(error, response){
}

and

Meteor.call("RemoveFromDatabase", "AvailablePlayers", this_id, function(error, response){
}

that way only one meteor method is needed to handle a removal to any collection. Is this possible? It wasn't working for me when I tried the following Meteor Method.

RemoveFromDatabase : function(collection, id){
   collection.remove(id);
} 

回答1:


Here is a working implementation of RemoveFromDatabase that can be shared between the client and the server:

Meteor.methods({
  RemoveFromDatabase: function(collectionName, id) {
    check(collectionName, String);
    check(id, String);

    var globalObject = Meteor.isServer ? global : window;
    var collection = globalObject[collectionName];
    if (collection instanceof Meteor.Collection) {
      return collection.remove(id);
    } else {
      throw new Meteor.Error(404, 'Cannot find the collection');
    }
  }
});

In general I'd strongly caution you against using this technique, because it allows literally anyone to remove any document from any collection as server-side code does not run though allow/deny methods. Avoiding these kinds of security holes are why people implement per-collection remove methods in the first place. At a minimum, you may want to check that the user is logged in, or that collectionName is in some acceptable subset.




回答2:


Yes it is possible: in javascript you need to use square bracket notation to get an object using a string variable, which means you need to work down from its parent. On the server, as elsewhere in Node.js, the global object is just global (it would be window on the client). So:

global[collection].remove(id);

should do it, provided you're referring to a valid collection (which you can check by seeing if collection in global returns true).




回答3:


I tried these a bit complex ways but then find the easies way - using the dburles:mongo-collection-instances package - https://atmospherejs.com/dburles/mongo-collection-instances It let's to access any collection by the collection name in variable:

let collName = "blabla";
Mongo.Collection.get(collName).find() // ... or any else


来源:https://stackoverflow.com/questions/25000146/is-it-possible-to-use-a-variable-in-a-meteor-collection-update-removal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!