我有一个由nodejs服务器和 mongodb 支持的 emberjs 应用程序。目前,我的数据库正在发送带有' _id' 字段的文档。我有以下代码强制Ember 对待' _id'作为主键:
App.ApplicationSerializer = DS.RESTSerializer.extend({
primaryKey: '_id'
});
另一方面,我有两个模型由一个& aMany'这样的关系:
App.Player = DS.Model.extend({
name: DS.attr('string'),
thumbLink: DS.attr('string'),
activeGame: DS.belongsTo('game', { async: true }),
email: DS.attr('string'),
firstName: DS.attr('string'),
lastName: DS.attr('string'),
admin: DS.attr('boolean')
});
App.Game = DS.Model.extend({
name: DS.attr('string'),
active: DS.attr('boolean'),
players: DS.hasMany('player', { async: true })
});
问题在于,当我尝试在我的控制器上保存模型(this.get('model').save()
)时,ID未被序列化,结果是ember发送以下内容:
{"game":{"name":"Indie/Rock","active":false,"players":[],"_id":"53cbbf43daa978983ee0b101"}}
正如您所看到的,播放器数组为空,因此,服务器正在保存那个实际上不正确的空数组。我知道可以在模型上使用{ embedded: true }
并从服务器返回带有嵌入文档的模型,但我想保留异步功能。
我试图从EmbeddedRecordsMixing
扩展游戏序列化,如下所示:
App.GameSerializer = DS.ActiveModelSerializer
.extend(DS.EmbeddedRecordsMixin)
.extend({
attrs: {
players: {serialize: 'ids', deserialize: 'ids'},
}
});
但是当我这样做时,我从ember中得到以下错误,即使ApplicationSerializer主动告诉Ember将用户_id作为主键:
Assertion Failed: Error: Assertion Failed: You must include an `id` for App.Game in a hash passed to `push`
我的问题是,是否可以维护ember-data的 async 功能,同时能够使用 ID 对其进行序列化文档的关系并使用_id作为主键。
谢谢。
答案 0 :(得分:3)
Ember Data在这方面是愚蠢的,如果它是ManyToOne关系,它只包含来自belongsTo
方的id。老实说,我已经在我的清单上提交了PR,但时间有限。
App.ApplicationSerializer = DS.RESTSerializer.extend({
serializeHasMany: function(record, json, relationship) {
var key = relationship.key;
var payloadKey = this.keyForRelationship ? this.keyForRelationship(key, "hasMany") : key;
var relationshipType = RelationshipChange.determineRelationshipType(record.constructor, relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany'
|| relationshipType === 'manyToOne') { // This is the change
json[payloadKey] = get(record, key).mapBy('id');
// TODO support for polymorphic manyToNone and manyToMany relationships
}
},
});