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

use*_*821 5 collections meteor

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

Client.insert({ name: "xyz", userid: "1", care:"health" });
Run Code Online (Sandbox Code Playgroud)

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

 If the form details are successfully inserted  - do one action
  else -another action
Run Code Online (Sandbox Code Playgroud)

所以请建议我做什么?

use*_*291 7

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
  }
);
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅文档


jer*_*tbt 5

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

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

成功时将返回_id插入的记录(执行被阻止,直到数据库确认写入)。您必须处理 a 中可能出现的错误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);
Run Code Online (Sandbox Code Playgroud)

感谢@user728291 的澄清。

  • 我不确定这是否正确。来自文档 - “在服务器上,如果不提供回调,则插入块直到数据库确认写入,或者如果出现问题则抛出异常。” 并且“在客户端上,插入永远不会阻塞。如果您不提供回调并且插入在服务器上失败,那么 Meteor 将向控制台记录警告。” (2认同)