用于embeds_many的原子addToSet - mongoid

时间:2013-08-20 08:00:32

标签: ruby-on-rails mongodb mongoid ruby-on-rails-4 mongoid3

我有以下操作:

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

其中states是一个状态文档数组。

模型有embeds_many:states

以某种方式返回: NoMethodError:#

的未定义方法` bson_dump '

我明白了什么不对吗?任何帮助都非常感谢

1 个答案:

答案 0 :(得分: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

$ rake test

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