我有一个正在事件处理程序中更新的集合,它正在更新集合,如果成功或失败,我想得到更新的结果,所以我可以根据其结果做一些逻辑。即重置会话值等。
我一直只是在if块中测试db动作本身的插入工作正常但是这似乎不适用于更新。
Template.customers_update.events({
'click a#cancel, click button#close' : function(event) {
event.preventDefault();
Session.set("editCustomer", false);
Session.set("customerId", null);
},
'click input[type=submit], submit form#create_customer' : function (event) {
event.preventDefault();
var customer_name = $("#customer_name").val();
var customer_address = $("#customer_address").val();
var customer_city = $("#customer_city").val();
var customer_state = $("#customer_state").val();
var customer_zip = $("#customer_zip").val();
var customer_phone = $("#customer_phone").val();
var customer_fax = $("#customer_fax").val();
var customer_eda = $("#eda_number").val();
var customer_duns = $("#duns_number").val();
if (Customers.update(Session.get("customerId"), {$set: {user_id: Meteor.user()._id, name: customer_name, address: customer_address, city: customer_city, state: customer_state, zip: customer_zip, phone: customer_phone, fax: customer_fax, eda_number: customer_eda, duns_number: customer_duns}})) {
console.log("Update Sucsess");
Session.set("editCustomer", false);
Session.set("customerId", null);
}
}
});
并在服务器中将其设置为允许并返回true
Customers.allow({
insert: function (userID, customer) {
return userID === customer.user_id;
},
update: function (userID, customer) {
return userID === customer.user_id;
},
remove: function (userID, customer) {
return userID === customer.user_id;
}
});
答案 0 :(得分:4)
使用第三个参数callback
(docs)
回调功能
可选。如果存在,则使用错误对象作为其参数调用。
答案 1 :(得分:3)
您的代码可能无法正常工作,因为.update()仅在服务器上引发异常。来自文档:
在服务器上,如果不提供回调,则更新块直到数据库确认写入,或者如果出现错误则抛出异常。如果确实提供了回调,则会立即返回更新。更新完成后,如果失败则调用带有单个错误参数的回调,如果更新成功则调用没有参数。
在客户端上,更新从不阻止。如果您不提供回调并且服务器上的更新失败,那么Meteor将向控制台记录警告。如果您提供回调,Meteor将在出现错误时使用错误参数调用该函数,如果更新成功则调用没有参数。
将其更改为:
var updateQuery = {$set: {user_id: Meteor.user()._id, name: customer_name, address: customer_address, city: customer_city, state: customer_state, zip: customer_zip, phone: customer_phone, fax: customer_fax, eda_number: customer_eda, duns_number: customer_duns}}
Customers.update(Session.get("customerId"), updateQuery, function (error) {
//on error do this
});