0

我有以下操作:

self.customers.where(.....).find_and_modify({ "$addToSet" => {:states => {"$each" => states }} }, new: true)

其中 states 是一组状态文档。

该模型具有 embeds_many :states

它以某种方式返回: NoMethodError: undefined method ` bson_dump ' for #

我理解错了吗?非常感谢任何帮助

4

1 回答 1

2

请记住,$each 的值必须是可以序列化为 BSON 的 Ruby 数组。如果你使用你的状态模型对象,它们的数组不能被序列化为 BSON。要将它们与 $each 一起使用,请在每个状态模型对象上使用 #serializeable_hash,如下所示。

测试/单元/customer_test.rb

require 'test_helper'
require 'json'
require 'pp'

class CustomerTest < ActiveSupport::TestCase
  def setup
    Customer.delete_all
  end

  test "find_and_modify with $addToSet and $each" do
    puts "\nMongoid::VERSION:#{Mongoid::VERSION}\nMoped::VERSION:#{Moped::VERSION}"
    customer = Customer.create('name' => 'John')
    customer.states << State.new('name' => 'New Jersey') << State.new('name' => 'New York')
    assert_equal 1, Customer.count

    states = [{'name' => 'Illinois'}, {'name' => 'Indiana'}]
    Customer.where('name' => 'John').find_and_modify({"$addToSet" => {:states => {"$each" => states}}}, new: true)
    assert_equal 4, Customer.first.states.size

    states = [State.new('name' => 'Washington'), State.new('name' => 'Oregon')]
    assert_raise NoMethodError do
      Customer.where('name' => 'John').find_and_modify({"$addToSet" => {:states => {"$each" => states}}}, new: true)
    end

    states = states.collect { |state| state.serializable_hash }
    Customer.where('name' => 'John').find_and_modify({"$addToSet" => {:states => {"$each" => states}}}, new: true)
    assert_equal 6, Customer.first.states.size

    pp JSON.parse(Customer.first.to_json)
  end
end

$耙子测试

Run options: 

# Running tests:

[1/1] CustomerTest#test_find_and_modify_with_$addToSet_and_$each
Mongoid::VERSION:3.1.5
Moped::VERSION:1.5.1
{"_id"=>"5273f65de4d30bd5c1000001",
 "name"=>"John",
 "states"=>
  [{"_id"=>"5273f65de4d30bd5c1000002", "name"=>"New Jersey"},
   {"_id"=>"5273f65de4d30bd5c1000003", "name"=>"New York"},
   {"_id"=>"5273f65de4d30bd5c1000006", "name"=>"Illinois"},
   {"_id"=>"5273f65de4d30bd5c1000007", "name"=>"Indiana"},
   {"_id"=>"5273f65de4d30bd5c1000004", "name"=>"Washington"},
   {"_id"=>"5273f65de4d30bd5c1000005", "name"=>"Oregon"}]}
Finished tests in 0.061650s, 16.2206 tests/s, 64.8824 assertions/s.              
1 tests, 4 assertions, 0 failures, 0 errors, 0 skips
于 2013-11-01T18:46:06.393 回答