简体   繁体   English

Ember-data和MongoDB,如何处理_id

[英]Ember-data and MongoDB, how to handle _id

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与rails和MongoDB结合使用,并且ID在MongoDB中的存储方式存在问题-在_id字段中。

Ember-data will use id as the default field for ID so I tried to override it like this: Ember-data将使用id作为ID的默认字段,因此我尝试像这样覆盖它:

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 未捕获的错误:断言失败:您的服务器返回了带有键_id的哈希,但是您没有映射

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? 我怀疑这可能是ember-data中的错误,因为它仍处于开发阶段,但是我试图找到一种方法来将_id映射到Rails服务器端的id上? I'm using mongoid to do the mongo mapping. 我正在使用mongoid进行mongo映射。

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 如果您使用的是Mongoid,那么这里有一个解决方案,因此您不必添加方法def id; object._id.to_s; end def id; object._id.to_s; end def id; object._id.to_s; end to every serializer def id; object._id.to_s; end每个序列化器

Add the following Rails initializer 添加以下Rails初始化程序

Mongoid 3.x Mongoid 3.x

module Moped
  module BSON
    class ObjectId
      alias :to_json :to_s
      alias :as_json :to_s
    end
  end
end

Mongoid 4 Mongoid 4

module BSON
  class ObjectId
    alias :to_json :to_s
    alias :as_json :to_s
  end
end

Active Model Serializer for Building 用于Building活动模型串行器

class BuildingSerializer < ActiveModel::Serializer
  attributes :id, :name
end

Resulting JSON 结果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 这是一个猴子通过补丁建议brentkirby和更新的Mongoid 4 arthurnn

An other way could be to use (if possible for you) the ActiveModel::Serializer . 另一种方法是使用ActiveModel :: Serializer (如果可能的话)。 (I think it should be close to rabl (?)) (我认为它应该接近rabl(?))

From the ember-data gihtub: https://github.com/emberjs/data : 从ember-data gihtub: https : //github.com/emberjs/data
Out of the box support for Rails apps that follow the active_model_serializers gem's conventions 对遵循active_model_serializers gem约定的Rails应用程序的开箱即用支持

When we began with ember-data we were crafting as_json() , but using the gem is definitely better :) 当我们从ember-data开始时,我们正在制作as_json() ,但是使用gem绝对更好:)

Ahh, instead of including _id in your JSON, you could craft the JSON to instead use the id method rather than the _id attribute. 啊,您可以将JSON改为使用id方法而不是_id属性,而不是在JSON中包含_id。 Ways: 方法:

You could use rabl , and the JSON could be like: 您可以使用rabl ,JSON可能像这样:

object @user 
attributes :id, :email
node(:full_name) {|user| "#{user.first_name} #{user.last_name}"}

You could also craft the as_json method 您也可以制作as_json方法

class User
  def as_json(args={})
    super args.merge(:only => [:email], :methods => [:id, :full_name])
  end
end

I had a similar problem using ember.js with ember-resource and couchdb, which also stores it's IDs as _id . 我在将ember.js与ember-resource和couchdb一起使用时遇到了类似的问题,该文件还将其ID存储为_id

As solution to this problem I defined a superclass for all my model classes containing a computed property to duplicate _id into id like this: 作为此问题的解决方案,我为我的所有模型类定义了一个超类,其中包含一个将_id复制到id的计算属性,如下所示:

// get over the fact that couchdb uses _id, ember-resource uses id
id: function(key, value) {
    // map _id (couchdb) to id (ember)
    if (arguments.length === 1) {
        return this.get('_id');
    }
    else {
        this.set('_id', value);
        return value;
    }
}.property('_id').cacheable()

Maybe this could solve your problem too? 也许这也可以解决您的问题?

The best way is to use ActiveModel::Serializers . 最好的方法是使用ActiveModel::Serializers Since we are using Mongoid , you will need to add an include statement like that (see this gist from benedikt): 由于我们使用的是Mongoid ,因此您需要添加一个include语句(请参见benedikt的要点 ):

# config/initializers/active_model_serializers.rb
Mongoid::Document.send(:include, ActiveModel::SerializerSupport)
Mongoid::Criteria.delegate(:active_model_serializer, :to => :to_a)

And then include your serializer. 然后包括您的序列化器。 Something like that: 像这样:

# app/serializers/user_serializer.rb
class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :email
  def id
    object._id
  end 
end

This fixes the _id problem 这解决了_id问题

The second part of joscas's answer fixed the id issue for me with Rails4/Ruby2 except I had to .to_s the _id. joscas回答的第二部分使用Rails4 / Ruby2为我解决了id问题,除了我必须.to_s _id。

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :email
  def id
    object._id.to_s
  end
end

If you use Mongoid3, here is the monkey patch may work for you. 如果您使用Mongoid3,以下是猴子补丁可能适合您的情况。

https://gist.github.com/4700909 https://gist.github.com/4700909

I don't know exactly when this was added, but you can just tell Ember-Data that the primaryKey is _id: 我不知道是什么时候添加的,但是您可以告诉Ember-Data primaryKey是_id:

DS.RESTAdapter.extend({
  serializer: DS.RESTSerializer.extend({
    primaryKey: '_id'
  })
});

Although the question is quite old but i still think my answer could help others: 尽管这个问题已经很老了,但我仍然认为我的回答可以帮助其他人:

If you are using ActiveModelSerializer then you just need to do this : 如果您使用的是ActiveModelSerializer,则只需执行以下操作:

class UserSerializer < ActiveModel::Serializer
     attributes :id , :name
end

It works all fine. 一切正常。 I am using emberjs on the front end btw. 我在前端btw上使用emberjs。

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

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