简体   繁体   中英

Atomic addToSet for embeds_many - mongoid

I have the following operation:

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

where states is an array of state documents.

The model has embeds_many :states

Somehow it returns: NoMethodError: undefined method ` bson_dump ' for #

Did I understand something wrong? Any help is really appreciated

Remember that the value for $each must be a Ruby array that can be serialized into BSON. If you use your state model objects, an array of them can't be serialized into BSON. To use them with $each, use #serializeable_hash on each state model object as in the following.

test/unit/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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM