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)
所以请建议我做什么?
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)
有关详细信息,请参阅文档
除了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 的澄清。
归档时间: |
|
查看次数: |
5403 次 |
最近记录: |