Ember-data and MongoDB, how to handle _id

后端 未结 9 812
别跟我提以往
别跟我提以往 2021-02-08 17:20

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 f

9条回答
  •  清歌不尽
    2021-02-08 17:53

    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 serializer

    Add 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

提交回复
热议问题