Skip to content

Commit

Permalink
don't set _id to default value for hash
Browse files Browse the repository at this point in the history
  • Loading branch information
Mike Dirolf committed Apr 24, 2009
1 parent 1c5bb14 commit 2dffc4b
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
9 changes: 4 additions & 5 deletions ext/cbson/cbson.c
Original file line number Diff line number Diff line change
Expand Up @@ -377,17 +377,16 @@ static void write_doc(bson_buffer* buffer, VALUE hash) {
int length_location = buffer_save_bytes(buffer, 4);

VALUE key = rb_str_new2("_id");
VALUE id = rb_hash_aref(hash, key);
if (TYPE(id) != T_NIL) {
if (rb_funcall(hash, rb_intern("has_key?"), 1, key) == Qtrue) {
VALUE id = rb_hash_aref(hash, key);
write_element_allow_id(key, id, (VALUE)buffer, 1);
}
key = ID2SYM(rb_intern("_id"));
id = rb_hash_aref(hash, key);
if (TYPE(id) != T_NIL) {
if (rb_funcall(hash, rb_intern("has_key?"), 1, key) == Qtrue) {
VALUE id = rb_hash_aref(hash, key);
write_element_allow_id(key, id, (VALUE)buffer, 1);
}


// we have to check for an OrderedHash and handle that specially
if (strcmp(rb_class2name(RBASIC(hash)->klass), "OrderedHash") == 0) {
VALUE keys = rb_funcall(hash, rb_intern("keys"), 0);
Expand Down
8 changes: 7 additions & 1 deletion lib/mongo/util/bson.rb
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,13 @@ def serialize(obj)
@buf.put_int(0)

# Write key/value pairs. Always write _id first if it exists.
oid = obj['_id'] || obj[:_id]
if obj.has_key? '_id'
oid = obj['_id']
elsif obj.has_key? :_id
oid = obj[:_id]
else
oid = false
end
serialize_key_value('_id', oid) if oid
obj.each {|k, v| serialize_key_value(k, v) unless k == '_id' || k == :_id }

Expand Down
8 changes: 8 additions & 0 deletions tests/test_db_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,14 @@ def test_hint
end
end

def test_hash_default_value_id
val = Hash.new(0)
val["x"] = 5
@@coll.insert val
id = @@coll.find_first("x" => 5)["_id"]
assert id != 0
end

# TODO this test fails with error message "Undefed Before end of object"
# That is a database error. The undefined type may go away.

Expand Down

0 comments on commit 2dffc4b

Please sign in to comment.