How to return mongo id as string in json response

I am using Rails 4.1.5 and Mongoid 4.0. My apis returns mongo id as hash

{
_id: {
$oid: "541e79bc616b684e75000000"
}
created_at: "2014-09-21T07:09:48.599Z"
}

I need something like this

{
id: "541e79bc616b684e75000000"
created_at: "2014-09-21T07:09:48.599Z"
}

I already checked this question , but I'm not sure which file I need to make the changes mentioned in this answer

+4
source share
1 answer

You need to create a file in config / initializers and put the code there.

UPDATE:

Use the following code:

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

    def as_json(*args)
      to_s.as_json
    end
  end
end
+10
source

All Articles