【问题标题】:How to apply function for all Collection如何为所有 Collection 应用功能
【发布时间】:2016-09-27 21:02:25
【问题描述】:

我想通过使用函数来更新我在server.js 中的收藏。 当我更改一个字段时,我需要更改多个集合。 我的问题是如何将参数用作集合名称。有什么办法吗,或者我必须为每个集合编写一个函数?

update: function(personID,option) {
  return Personel.update(
    { id: personID },
    { $set: option },
    { multi: true }
  );
},

我想将此逻辑应用于单独的集合。

【问题讨论】:

    标签: node.js meteor collections


    【解决方案1】:

    你可以试试这个方法:

    var Personel = new Mongo.Collection('personel');
    var Items = new Mongo.Collection('items');
    var SomeOtherCollection = new Mongo.Collection('someOtherCollection');
    
    ....
    
    update: function(personID, option, collectionName) {
      // Choose collection by given name
      var Collection = {
        Personel: Personel,
        Items: Items,
        SomeOtherCollection: SomeOtherCollection
      }[collectionName];
    
      return Collection.update(
        { id: personID },
        { $set: option },
        { multi: true }
      );
    },
    

    【讨论】:

      【解决方案2】:

      这个问题有一个更棘手的解决方法。您实际上需要将所有集合绑定到一个对象中。

      CollectionList = {};
      
      CollectionList.Personel = new Mongo.Collection('personel');
      CollectionList.secondCollection = new Mongo.Collection('second');
      

      之后,您将集合名称作为字符串传递给方法。

      update: function(collectionName,personID,option){
           return CollectionList[collectionName].update(
                   //..rest of your code
                  );
      

      【讨论】:

      • 在客户端您可以在this.globalwindow.global下找到集合,即this.global['Personel']指的是Personel集合。这避免了创建您自己的对象的需要。
      • 再次感谢@MichelFloyd。总有一些新东西要向你学习。我以前不知道。
      猜你喜欢
      • 2021-09-20
      • 2016-11-19
      • 2021-01-27
      • 1970-01-01
      • 2021-04-08
      • 2014-11-18
      • 1970-01-01
      • 2013-07-25
      • 2018-03-22
      相关资源
      最近更新 更多