必须 to_json 返回一个 mongoid 作为字符串

问题描述 投票:0回答:7

在我的 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
ruby-on-rails mongoid
7个回答
12
投票

你可以猴子补丁

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 对象表现得更加明智。


8
投票

对于使用 Mongoid 4+ 的人使用这个,

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

参考


8
投票

您可以在

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",
    ...
}

0
投票

例如使用:

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

这次回归

{
    "_id": "54ed1e9896188813b0000001"
}

0
投票
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

0
投票
# config/initializers/mongoid.rb

# convert object key "_id" to "id" and remove "_id" from displayed attributes on mongoid documents when represented as JSON
module Mongoid
  module Document
    def as_json(options={})
      attrs = super(options)
      id = {id: attrs["_id"].to_s}
      attrs.delete("_id")
      id.merge(attrs)
    end
  end
end

# converts object ids from BSON type object id to plain old string
module BSON
  class ObjectId
    alias :to_json :to_s
    alias :as_json :to_s
  end
end

0
投票

如果您不想更改 MongoId 的默认行为,只需转换 as_json 的结果即可。

profile.map{|k, v| [k, v&.[]('$oid') || v]}.to_h

此外,这还可以转换其他

BSON::ObjectId
,例如
user_id

© www.soinside.com 2019 - 2024. All rights reserved.