我是MongoDB和Backbone的新手,所以我試圖理解它們,但它很難。我有一個很大的問題:我無法理解如何操作Backbone.Model中的屬性以便在視圖中使用我所需要的。更具體的 - 我有一個模式:MongoError:無法更改文檔的_id
window.User = Backbone.Model.extend({
urlRoot:"/user",
idAttribute: "_id",
defaults: {
_id: null,
name: "",
email: "[email protected]"
}
});
window.UserCollection = Backbone.Collection.extend({
model: User,
url: "user/:id"
});
而且我有一個查看:
beforeSave: function(){
var self = this;
var check = this.model.validateAll();
if (check.isValid === false) {
utils.displayValidationErrors(check.messages);
return false;
}
this.saveUser();
return false;
},
saveUser: function(){
var self = this;
console.log('before save');
this.model.save(null, {
success: function(model){
self.render();
app.navigate('user/' + model.id, false);
utils.showAlert('Success!', 'User saved successfully', 'alert-success');
},
error: function(){
utils.showAlert('Error', 'An error occurred while trying to save this item', 'alert-error');
}
});
}
我不得不使用從除「_id」任何領域「放」的方法白衣數據,所以它必須是水木清華這樣的:
{"name": "Foo", "email": "[email protected]"}
但每一次,不取決於我做什麼它發送
{**"_id": "5083e4a7f4c0c4e270000001"**, "name": "Foo", "email": "[email protected]"}
,並從服務器這個錯誤:
MongoError: cannot change _id of a document old:{ _id: ObjectId('5083e4a7f4c0c4e270000001'), name: "Foo" } new:{ _id: "5083e4a7f4c0c4e270000001", name: "Bar", email: "[email protected]" }
Github上鍊接:https://github.com/pruntoff/habo
提前感謝!
當你調用'model.save()'是一個後正在執行或PUT? – InPursuit
它被執行。 'app.get('/ user /:id',usr.findById); app.put('/ user /:id',usr.updateUser);' – Pruntoff
如果骨幹在你調用'save'時做了PUT,那麼模型的idAttribute(你的情況下是_id)不應該被髮送。你可以在'save()'之前在模型上調用'isNew()'並驗證它是否返回'false'?在調用save()之前,請確認'this.model.id'不爲空或未定義。 – InPursuit