Имейте to_json вернуть мангоид как строку
В моем 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
Ответы
Ответ 1
Вы можете патч обезьяны 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
Это сделает все ваши монгоидные объекты разумными.
Ответ 2
Для парней, использующих Mongoid 4+, используйте это,
module BSON
class ObjectId
alias :to_json :to_s
alias :as_json :to_s
end
end
Ссылка
Ответ 3
Вы можете изменить данные в методе 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",
...
}
Ответ 4
Используйте, например:
user = collection.find_one(...)
user['_id'] = user['_id'].to_s
user.to_json
этот возврат
{
"_id": "54ed1e9896188813b0000001"
}
Ответ 5
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