Ember-data和MongoDB,如何处理_id [英] Ember-data and MongoDB, how to handle _id
问题描述
Ember-data将使用ID作为ID的默认字段,所以我试图重写它:
App.User = DS.Model。扩展
primaryKey:_id
名称:DS.attrstring
image:DS.attrstring
这似乎大部分时间都可以工作,但在某些情况下,我收到了ember的异常说:
未捕获错误:断言失败:您的服务器使用
键_id返回散列,但您没有映射
我怀疑这可能是垃圾数据中的一个错误,因为它仍然在很大的开发中,但是我试图找到一种方法来在服务器端映射_id到id?我正在使用mongoid来做mongo映射。
如果你在这里使用Mongoid是一个使你这样做的解决方案不必添加方法 def id; object._id.to_s;结束
到每个序列化程序
添加以下Rails初始化程序
Mongoid 3.x
模块Moped
模块BSON
类ObjectId
别名:to_json:to_s
别名:as_json:to_s
end
end
end
Mongoid 4
模块BSON
class ObjectId
别名:to_json:to_s
别名:as_json:to_s
end
end
活动模型序列化器为构建
class BuildingSerializer< ; ActiveModel :: Serializer
属性:id,:name
end
产生的JSON
{
/ pre>
buildings:[
{id:5338f70741727450f8000000,name :City Hall},
{id:5338f70741727450f8010000,name:Firestation}
]
}
这是由 brentkirby ,并通过 arthurnn
I'm using ember-data with rails and MongoDB and am having problem with the way IDs are stored in MongoDB - in a _id field.
Ember-data will use id as the default field for ID so I tried to override it like this:
App.User = DS.Model.extend primaryKey: "_id" name: DS.attr "string" image: DS.attr "string"
This seems to work most of the time but in some instances I get exceptions from ember saying:
Uncaught Error: assertion failed: Your server returned a hash with the key _id but you have no mappings
I suspect this might be a bug in ember-data because it's still heavily under development, but I was trying to find a way to get to map _id to id on the server side in rails? I'm using mongoid to do the mongo mapping.
解决方案If you are using Mongoid here is a solution that makes it so you don't have to add a method
def id; object._id.to_s; end
to every serializerAdd the following Rails initializer
Mongoid 3.x
module Moped module BSON class ObjectId alias :to_json :to_s alias :as_json :to_s end end end
Mongoid 4
module BSON class ObjectId alias :to_json :to_s alias :as_json :to_s end end
Active Model Serializer for
Building
class BuildingSerializer < ActiveModel::Serializer attributes :id, :name end
Resulting JSON
{ "buildings": [ {"id":"5338f70741727450f8000000","name":"City Hall"}, {"id":"5338f70741727450f8010000","name":"Firestation"} ] }
This is a monkey patch suggested by brentkirby and updated for Mongoid 4 by arthurnn
这篇关于Ember-data和MongoDB,如何处理_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!