有to_json返回一个mongoid作为字符串

在我的Rails API中,我希望Mongo对象作为JSON字符串返回,其中Mongo UID作为“id”属性而不是“_id”对象。

我希望我的API返回以下JSON:

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

代替:

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

我的型号代码是:

 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 

你可以猴子修补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 

处理$oid东西然后Mongoid::Document_id转换为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 

这将使你所有的Mongoid对象表现得很明智。

对于使用Mongoid 4+的人来说,

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

参考

您可以在as_json方法中更改数据,而数据是哈希:

 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 

结果:

 { "id": "536268a06d2d7019ba000000", ... } 

用例如:

 user = collection.find_one(...) user['_id'] = user['_id'].to_s user.to_json 

这回归

 { "_id": "54ed1e9896188813b0000001" } 
 class Profile include Mongoid::Document field :name, type: String def to_json as_json(except: :_id).merge(id: id.to_s).to_json end end