diff --git a/lib/mongo/db.rb b/lib/mongo/db.rb index bb51dbb..160c71a 100644 --- a/lib/mongo/db.rb +++ b/lib/mongo/db.rb @@ -475,9 +475,13 @@ module XGen objects.collect! { |o| @pk_factory.create_pk(o) } + else + objects = objects.collect do |o| + o[:_id] || o['_id'] ? o : o.merge(:_id => ObjectID.new) + end end send_to_db(InsertMessage.new(@name, collection_name, true, *objects)) - objects + objects.collect { |o| o[:_id] || o['_id'] } } end diff --git a/tests/test_db.rb b/tests/test_db.rb index 09d327a..68a13f6 100644 --- a/tests/test_db.rb +++ b/tests/test_db.rb @@ -66,19 +66,20 @@ class DBTest < Test::Unit::TestCase coll = db.collection('test') coll.clear + insert_id = coll.insert('name' => 'Fred', 'age' => 42) # new id gets added to returned object - obj = coll.insert('name' => 'Fred', 'age' => 42) row = coll.find_first({'name' => 'Fred'}, :limit => 1) oid = row['_id'] assert_not_nil oid - assert_equal obj, row + assert_equal insert_id, oid oid = XGen::Mongo::Driver::ObjectID.new - obj = coll.insert('_id' => oid, 'name' => 'Barney', 'age' => 41) - row = coll.find_first({'name' => 'Barney'}, :limit => 1) + data = {'_id' => oid, 'name' => 'Barney', 'age' => 41} + coll.insert(data) + row = coll.find_first({'name' => data['name']}, :limit => 1) db_oid = row['_id'] assert_equal oid, db_oid - assert_equal obj, row + assert_equal data, row coll.clear end diff --git a/tests/test_db_api.rb b/tests/test_db_api.rb index b00eaa0..39b8f5e 100644 --- a/tests/test_db_api.rb +++ b/tests/test_db_api.rb @@ -13,7 +13,8 @@ class DBAPITest < Test::Unit::TestCase def setup @@coll.clear - @r1 = @@coll.insert('a' => 1) # collection not created until it's used + @r1 = {'a' => 1} + @@coll.insert(@r1) # collection not created until it's used @@coll_full_name = 'ruby-mongo-test.test' end @@ -29,8 +30,8 @@ class DBAPITest < Test::Unit::TestCase end def test_insert - @@coll.insert('a' => 2) - @@coll.insert('b' => 3) + assert_kind_of ObjectID, @@coll.insert('a' => 2) + assert_kind_of ObjectID, @@coll.insert('b' => 3) assert_equal 3, @@coll.count docs = @@coll.find().to_a @@ -46,7 +47,11 @@ class DBAPITest < Test::Unit::TestCase end def test_insert_multiple - @@coll.insert({'a' => 2}, {'b' => 3}) + ids = @@coll.insert({'a' => 2}, {'b' => 3}) + + ids.each do |i| + assert_kind_of ObjectID, i + end assert_equal 3, @@coll.count docs = @@coll.find().to_a @@ -614,7 +619,7 @@ class DBAPITest < Test::Unit::TestCase a = {"hello" => "world"} - @@coll.save(a) + assert_kind_of ObjectID, @@coll.save(a) assert_equal 1, @@coll.count @@coll.save(@@coll.find_first)