2014-01-17 132 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。