gpt4 book ai didi

javascript - 更新记录时的主干模型和 idAttribute

转载 作者:行者123 更新时间:2023-11-29 22:17:16 25 4
gpt4 key购买 nike

我正在使用 mongoLab,模型 ID 如下所示

"_id": {
"$oid": "50f9a0f5e4b007f27f766cf3"
},

我正在使用 idAttribute 将模型 ID 设置为 _id,在我尝试更新模型之前一切正常。

因为 _id 属性存在于模型中,所以我在尝试插入时遇到错误。

我需要从我的属性中删除属性 _id 吗?我假设 Backbone 的魔力会适本地清理属性

最佳答案

您需要删除 _id 属性。

在 MongoLab REST API 中,id 不是数据负载本身的一部分,但并非所有后端都如此。对于 Backbone 而言,假设 id 应该出现在有效载荷中可能比假设它不应该出现更有意义。

也就是说,没有真正的方法让 Backbone 自动清除有效负载中的 id。没有猴子修补/重写太多代码的最佳选择可能是覆盖 Model#toJSON,类似于:

Backbone.Model.prototype.toJSON = function (options) {
var attrs = _.clone(this.attributes);
// In this case you'd have to pass `includeId: true` to `toJSON` when you
// actually *want* the _id in the output.
return options && options.includeId ? attrs : _.omit(attrs, '_id');
};

你也可以使用 monkeypatch sync,比如:

var sync = Backbone.sync;
Backbone.sync = function (method, model, options) {
options || (options = {});
// if options.attrs is present, Backbone will use it over dumping toJSON
if (!options.attrs) options.attrs = _.omit(model.attributes, '_id');
return sync.call(Backbone, method, model, options);
};

关于javascript - 更新记录时的主干模型和 idAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14410440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com