2014-01-17 82 views
7

当我尝试插入某个集合时,在控制台中获取此错误:流星允许Upsert?

“更新失败:访问被拒绝。在限制集合中不允许插入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); 
}; 

回答

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); 
+0

谢谢!那就是诀窍。我还成功地分解了插入和更新,并使用$ set。 – user3203772

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。