-
Type: Task
-
Resolution: Done
-
Affects Version/s: None
-
Component/s: None
I've ran into an odd bug related to $addToSet on has_and_belongs_to_many model_ids field. When I try to add an id to the field using {{Model.update "$addToSet" =>
{model_ids: id}}} Mongoid inserts [id] - a single element array instead of just id. This also happens with update_all, but not with add_to_set :model_ids, id call. It does not happen when the field is simply defined as an Array type instead of many-to-many relation (field :model_ids, type: Array). Here's a short test script.
#!/usr/bin/env ruby require 'mongoid' Mongoid.configure do |config| config.connect_to "mongoid_test" end Moped.logger = Logger.new(STDOUT) class Tag include Mongoid::Document end class A include Mongoid::Document end def test_add_to_set value @a ||= A.create puts "\n\n" A.where(_id: @a.id).update_all('$addToSet' => {tag_ids: value}) @a.reload puts "======= Last id: #{@a.tag_ids.last.inspect}" puts "======= Error!" if @a.tag_ids.last.kind_of? Array end test_add_to_set 1 class A has_and_belongs_to_many :tags, inverse_of: nil end test_add_to_set 2
And here's the output:
MOPED: 127.0.0.1:27017 INSERT database=mongoid_test collection=as documents=[{"_id"=>"52305e0266d9f1e3f6000001"}] flags=[] (0.1080ms) MOPED: 127.0.0.1:27017 UPDATE database=mongoid_test collection=as selector={"_id"=>"52305e0266d9f1e3f6000001"} update={"$addToSet"=>{:tag_ids=>1}} flags=[:multi] (0.1230ms) MOPED: 127.0.0.1:27017 QUERY database=mongoid_test collection=as selector={:_id=>"52305e0266d9f1e3f6000001"} flags=[] limit=-1 skip=0 batch_size=nil fields=nil (4.4219ms) ======= Last id: 1 MOPED: 127.0.0.1:27017 UPDATE database=mongoid_test collection=as selector={"_id"=>"52305e0266d9f1e3f6000001"} update={"$addToSet"=>{:tag_ids=>[2]}} flags=[:multi] (0.1390ms) MOPED: 127.0.0.1:27017 QUERY database=mongoid_test collection=as selector={:_id=>"52305e0266d9f1e3f6000001"} flags=[] limit=-1 skip=0 batch_size=nil fields=nil (0.3378ms) ======= Last id: [2] ======= Error!