【问题标题】:Mongo Insert Inside of a Meteor Method?Mongo 在 Meteor 方法中插入?
【发布时间】:2014-10-30 19:15:53
【问题描述】:

在我的 Meteor 应用程序中,我有一个 Meteor 方法,它将集合作为参数并尝试在该集合上运行 mongo insert 命令以创建新文档。该代码使用setInterval 每 10 秒运行一次。

集合已定义:

My_Collection_Name = new Meteor.Collection('my_collection_name');


服务器代码:
var collection = My_Collection_Name;
var data = [1,2,3,'a','b','c'];
Meteor.call('createDocument', collection, data);


方法:
Meteor.methods({
  createDocument: function(collection, data) {
    collection.insert({
      data: data
    });
  }
});


但是,这会在控制台中返回以下错误:
I20141030-14:58:06.716(-4)? Exception in setInterval callback: TypeError: Object #<Object> has no method 'insert'

为什么这不起作用?是否可以将集合作为参数传递?提前谢谢!

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    发生的情况是您在客户端和服务器上有不同的 集合(在Understanding Meteor publish/subscribe 上阅读更多信息)。依赖 ~private _collection 字段是有风险的。您确实想要将集合名称作为字符串传递给 Meteor.call,确保您在服务器上为集合具有相同的变量名称,并在 global 对象中通过集合名称查找集合服务器:

    // on the client:
    
    MyCollection = new Mongo.Collection('record-set-name');  // set server-side by .publish()
    Meteor.call('createDocument', 'MyCollection', data);
    
    // on the server:
    MyCollection = new Mongo.Collection('collection-name-in-mongo');
    Meteor.methods({
      createDocument: function(collectionName, data) {
        global[collectionName].insert({
          data: data
        });
      }
    });
    

    meteor-autocomplete 使用这个模式到pass collection names from the client to the server

    Understanding Meteor publish/subscribe 解释了集合名称和集合变量名称在 Mongo 中的关系。

    【讨论】:

    • 精彩的答案,高效,正是我想要的。谢谢丹!
    【解决方案2】:

    在进一步检查集合对象后,我注意到它有一个_collection 对象,其中又包含insertupdate 等函数。因此,将代码调整为以下代码可以解决在 Meteor 方法中针对集合参数运行 Mongo 命令的问题:

    Meteor.methods({
      createDocument: function(collection, data) {
        collection._collection.insert({
          data: data
        });
      }
    });
    

    【讨论】:

    • 这不必要地将整个对象传递给服务器,并假设集合在客户端的名称与服务器上的发布相同。检查my answer 以获得正确的解决方案。
    【解决方案3】:

    我认为这里 collection 变量被用作集合名称,如果您的集合名称很少,您可以在服务器方法中执行如下操作

    Meteor.methods({
      createDocument: function(collection, data) {
        if(collection == "firstcollection")
        {
          firstcollection.insert({
            data: data
          });
       }
       else if(collection == "secondcollection")
        {
          secondcollection.insert({
            data: data
          });
       }
      }
    });
    

    【讨论】:

    • 感谢您的回复。但是,我的集合变量不是字符串,而是对象。所以我不能像那样进行字符串检查,我认为尝试插入字符串也行不通。
    猜你喜欢
    • 2014-08-02
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 2016-02-26
    • 1970-01-01
    相关资源
    最近更新 更多