尝试插入集合时在控制台中出现此错误:
“更新失败:访问被拒绝。限制集合中不允许进行Upsert。”
以下是我指定的允许规则:
if (Meteor.isClient) {
Meteor.subscribe('customers');
}
customers = Customers
if (Meteor.isServer) {
Meteor.publish('customers', function() {
return customers.find();
});
customers.allow({
insert: function (document) {
return true;
},
update: function () {
return true;
},
remove: function () {
return true;
}
});
}
这是upsert部分:
Customer.prototype.create = function ( name, address, phone, cell, email, website, contact, shipping ) {
var attr = {
name : name,
address : address,
phone : phone,
cell : cell,
email : email,
website : website,
contact : contact,
shipping : shipping
};
Customers.upsert( Customers.maybeFindOne( attr )._id, attr );
return new Customer( attr );
};
答案 0 :(得分:8)
这是a choice the development team。
建议的解决方案是编写一个包装upsert的方法。这使得服务器请求来自服务器代码,而客户端代码仅运行延迟补偿。例如:
//shared code
Meteor.methods({
customersUpsert: function( id, doc ){
Customers.upsert( id, doc );
}
});
//called from client
Meteor.call( 'customersUpsert', Customers.maybeFindOne( attr )._id, attr );
答案 1 :(得分:1)
这是我使用的解决方法(使用下划线默认功能):
_upsert: function(selector, document) {
if (this.collection.findOne(selector) != null) {
this.collection.update(selector, {
$set: document
});
} else {
this.collection.insert(_.defaults({
_id: selector
}, document));
}
}
假设selector
是对象ID。