我是 MongoDB 和 Backbone 的新手,所以我尝试理解它们,但这很难。我有一个很大的问题:我无法理解如何操作 Backbone.Model 中的属性以仅在 View 中使用我需要的。更具体 - 我有一个模型:
window.User = Backbone.Model.extend({
urlRoot:"/user",
idAttribute: "_id",
defaults: {
_id: null,
name: "",
email: "foo@bar.baz"
}
});
window.UserCollection = Backbone.Collection.extend({
model: User,
url: "user/:id"
});
我有一个 View :
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');
}
});
}
我必须使用 'put' 方法来处理除 '_id' 之外的任何字段的数据,所以它必须是这样的:
{"name": "Foo", "email": "foo@bar.baz"}
但每次,并不取决于我发送的内容
{**"_id": "5083e4a7f4c0c4e270000001"**, "name": "Foo", "email": "foo@bar.baz"}
来自服务器的这个错误:
MongoError: cannot change _id of a document old:{ _id: ObjectId('5083e4a7f4c0c4e270000001'), name: "Foo" } new:{ _id: "5083e4a7f4c0c4e270000001", name: "Bar", email: "foo@bar.baz" }
Github 链接:https://github.com/pruntoff/habo
提前致谢!
最佳答案
通过查看您的 mongo 错误,问题不在于 mongo,它只是在做它应该做的事情。它有一个 _id 为 ObjectId 类型的对象:ObjectId('xxx'),现在您尝试将该对象更改为具有 String 类型的 _id (_id: "5083e4a7f4c0c4e270000001") 并且 Mongo 显然不喜欢。
所以,问题是:为什么对象首先有一个 ObjectId 类型的 id?第一次是怎么设置的?如果您使用其他方法来初始化它(我猜是服务器端),您应该将 id 类型设置为 String ,以便它与来自脚本库的相同。如果您希望它保持为 ObjectId,则需要将来自脚本的字符串转换为 ObjectId,然后再将其保存到 Mongo。
HTH。
关于javascript - MongoError : cannot change _id of a document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13031541/
相关文章:
mongodb - Azure:不支持 DocumentDB Mongo $group
mongodb - 如何在 $lookup Mongodb 的 LocalField 中将字符串转换
mongodb - Spark 流 : foreachRDD update my mongo RDD
mongodb - 在mongo聚合中将ObjectID转换为字符串
javascript - Mongoose 连接到 MongoDB Atlas 的最佳池大小是多少?
mongodb - 在集合之间移动文档是表示 MongoDB 中状态变化的好方法吗?
ruby-on-rails - MongoDB 的最佳分析/数据可视化库
javascript - 在 MongoDB 中按字母顺序对文档进行排序(也称为自然排序顺序,人类排