在 Mongo 数据库中插入 Ruby 个对象的数组

Insert an array of Ruby objects in a Mongo database

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

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

其中@board 是 Board 的实例 class。

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>

我正在使用的宝石:'sinatra'、'mongo (2.0.4)' 和 'bson_ext'(都需要使用 Bundler.require)。谢谢!

您可以简单地将@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/