繁体   English   中英

MongoError:无法更改文档的_id

[英]MongoError: cannot change _id of a document

我是MongoDB和Backbone的新手,所以我试着理解它们,但这很难。 我有一个很大的问题:我无法理解如何操纵Backbone.Model中的属性只在我需要的视图中使用。 更具体 - 我有一个模型

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"
});

我有一个观点

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”之外的任何字段的'put'方法whit数据,所以它必须像:

{"name": "Foo", "email": "foo@bar.baz"}

但每一次,都不依赖于我发送的东西

{**"_id": "5083e4a7f4c0c4e270000001"**, "name": "Foo", "email": "foo@bar.baz"}

和来自服务器的此错误:

MongoError:无法更改旧文档的_id:{_ id:ObjectId('5083e4a7f4c0c4e270000001'),名称:“Foo”} new:{_ id:“5083e4a7f4c0c4e270000001”,名称:“Bar”,电子邮件:“foo@bar.baz” }

Github链接: https//github.com/pruntoff/habo

提前致谢!

从查看你的mongo错误来看,问题不在于mongo,它正在做它应该做的事情。 它有一个ObjectId类型为_id的对象:ObjectId('xxx'),现在你试图将该对象改为具有String类型的_id(_id:“5083e4a7f4c0c4e270000001”),并且Mongo显然不喜欢。

所以,问题是:为什么对象首先具有ObjectId类型的id? 你是怎么第一次设置它的? 如果您使用其他方法来初始化它(我猜服务器端),您应该将id类型设置为String,以便它与来自脚本库的类型相同。 如果您希望它保留ObjectId,则需要将来自脚本的String转换为ObjectId,然后再将其保存到Mongo。

HTH。

MongoDB 创建 _id作为ObjectID,但不检索 _id作为ObjectID。

无论这种不一致是否是“正确的行为”,对于大多数MongoDB用户来说,这肯定是一个令人讨厌的惊喜。

你可以修复它:

if ( this._id && ( typeof(this._id) === 'string' ) ) {
  log('Fixing id')
  this._id = mongodb.ObjectID.createFromHexString(this._id)
}

请参阅MongoDB无法更新文档,因为_id是字符串,而不是ObjectId

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM