Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return mongo id as string in json response

I am using Rails 4.1.5 & Mongoid 4.0. My apis are returning mongo id's as hash

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

I want something like this

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

I have checked this question already, but i am not sure in which file i need to put changes mentioned in this answer

like image 791
Akhil Avatar asked Sep 22 '14 06:09

Akhil


1 Answers

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
like image 125
Zakwan Avatar answered Oct 02 '22 15:10

Zakwan