【问题标题】:Insert an array of Ruby objects in a Mongo database在 Mongo 数据库中插入一组 Ruby 对象
【发布时间】:2015-06-10 23:44:15
【问题描述】:

所以,我正在使用 Ruby MongoDB 驱动程序,我想像这样插入和对象:

 db.insert_one({
  'game_id' => @token,
  'board' => {
    'tiles' => @board.tiles
  }
})

@board 是 Board 类的一个实例。

class Board
 attr_accessor :tiles
  def initialize()
    @tiles = [Tile.new, Tile.new]
  end
end

和瓷砖

class Tile
  def initialize()
    @x = 1, @y = 1
  end
  def to_json(options)
    {"x" => @x, "y" => @y}.to_json
  end
end

所以最后,'tiles' 字段应该如下所示:

'tiles': [{x:1, y:1}, {x:1, y:1}]

我收到此错误:

undefined method `bson_type' for #<Tile:0x007ff7148d2440>

我正在使用的 gem:'sinatra'、'mongo (2.0.4)' 和 'bson_ext'(所有这些都需要使用 Bundler.require)。谢谢!

【问题讨论】:

  • 错误告诉你驱动不知道怎么把Tile实例放到MongoDB里面,MongoDB不知道怎么处理Tiles没有人会自动调用to_json给你。
  • 我尝试调用 to_json,但它会将内容作为字符串(一个 json 字符串)插入,而不是作为数组。
  • to_json 返回一个字符串,as_json 返回一个哈希。是的,命名有点混乱。抱歉,这不是我最清楚的评论。

标签: ruby mongodb-ruby


【解决方案1】:

您可以简单地将 @board.tiles 从 Objects 的集合转换为 ruby​​ Hashes 的集合:

class Tile
  def initialize()
    @x = 1, @y = 1
  end
  def raw_data
    {"x" => @x, "y" => @y}
  end
end

db.insert_one({
  'game_id' => @token,
  'board' => {
    'tiles' => @board.tiles.map(&:raw_data)
  }
})

对于更复杂的事情,我建议你使用 mongoid http://mongoid.org/en/mongoid/

【讨论】:

  • (我现在无法证明代码)但这会插入一个 (json ) 字符串而不是数组,对吧?我知道 Mongoid,我只是认为我的问题很容易使用本机驱动程序:p 谢谢!
  • @enrmarc 你几乎是对的。我的解决方案有问题。它将tiles 转换为字符串数组。但现在我修改它以返回一个哈希数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-04
  • 1970-01-01
  • 2019-06-28
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多