如何检查Collections.insert()是否成功插入Meteor中?

时间:2014-02-10 08:27:12

标签: collections meteor

如何检查(用户创建的集合)Collections.insert()是否成功插入Meteor JS?例如,我使用客户端集合来插入详细信息,如下所示:

Client.insert({ name: "xyz", userid: "1", care:"health" });

如何知道上面的插入查询是否成功插入?由于以下问题

 If the form details are successfully inserted  - do one action
  else -another action

所以请建议我做什么?

2 个答案:

答案 0 :(得分:5)

Insert在回调函数的参数中提供服务器响应。它提供了两个参数'error'和'result',但其中一个将始终为null,具体取决于插入是否成功。

Client.insert( { name: "xyz", userid: "1", care:"health" }
  , function( error, result) { 
    if ( error ) console.log ( error ); //info about what went wrong
    if ( result ) console.log ( result ); //the _id of new object if successful
  }
);

有关详细信息,请参阅documentation

答案 1 :(得分:4)

除了user728291使用回调的答案之外,您还可以在服务器上执行以下操作:

var value = Collection.insert({foo: bar});

将成功返回插入记录的_id(执行被阻止,直到db确认写入)。您将不得不在try...catch中处理可能的错误,但有时回调只是有点麻烦:)

所以这也适用于服务器:

try {
    var inserted = Collection.insert({foo: bar});
} 
catch (error) {
    console.log("Could not insert due to " + error);
}

if (inserted)
    console.log("The inserted record has _id: " + inserted);

感谢@ user728291的澄清。