Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have to_json return a mongoid as a string

In my Rails API, I'd like a Mongo object to return as a JSON string with the Mongo UID as an "id" property rather than as an "_id" object.

I want my API to return the following JSON:

{
    "id": "536268a06d2d7019ba000000",
    "created_at": null,
}

Instead of:

{
    "_id": {
        "$oid": "536268a06d2d7019ba000000"
    },
    "created_at": null,
}

My model code is:

class Profile
  include Mongoid::Document
  field :name, type: String

  def to_json(options={})
    #what to do here?
    # options[:except] ||= :_id  #%w(_id)
    super(options)
  end
end
like image 727
MonkeyBonkey Avatar asked May 06 '14 21:05

MonkeyBonkey


3 Answers

You can change the data in as_json method, while data is a hash:

class Profile
  include Mongoid::Document
  field :name, type: String

   def as_json(*args)
    res = super
    res["id"] = res.delete("_id").to_s
    res
  end
end

p = Profile.new
p.to_json

result:

{
    "id": "536268a06d2d7019ba000000",
    ...
}
like image 55
ole Avatar answered Nov 02 '22 18:11

ole


For guys using Mongoid 4+ use this,

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

Reference

like image 37
Ronak Jain Avatar answered Nov 02 '22 17:11

Ronak Jain


You can monkey patch Moped::BSON::ObjectId:

module Moped
  module BSON
    class ObjectId   
      def to_json(*)
        to_s.to_json
      end
      def as_json(*)
        to_s.as_json
      end
    end
  end
end

to take care of the $oid stuff and then Mongoid::Document to convert _id to id:

module Mongoid
  module Document
    def serializable_hash(options = nil)
      h = super(options)
      h['id'] = h.delete('_id') if(h.has_key?('_id'))
      h
    end
  end
end

That will make all of your Mongoid objects behave sensibly.

like image 12
mu is too short Avatar answered Nov 02 '22 19:11

mu is too short