Have to_json return a mongoid as a string

前端 未结 6 960
名媛妹妹
名媛妹妹 2020-12-09 19:00

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 retu

6条回答
  •  春和景丽
    2020-12-09 19:31

    If you don't want to change default behavior of MongoId, just convert result of as_json.

    profile.as_json.map{|k,v| [k, v.is_a?(BSON::ObjectId) ? v.to_s : v]}.to_h
    

    Also, this convert other BSON::ObjectId like user_id.

提交回复
热议问题