diff --git a/lib/mongo/db.rb b/lib/mongo/db.rb index 69e254e..51f064a 100644 --- a/lib/mongo/db.rb +++ b/lib/mongo/db.rb @@ -372,6 +372,11 @@ module XGen raise "Error with count command: #{doc.inspect}" end + # Dereference a DBRef, getting the document it points to. + def dereference(dbref) + collection(dbref.namespace).find_first("_id" => dbref.object_id) + end + # Evaluate a JavaScript expression on MongoDB. # +code+ should be a string or Code instance containing a JavaScript # expression. Additional arguments will be passed to that expression diff --git a/tests/test_db_api.rb b/tests/test_db_api.rb index 5675514..13303b5 100644 --- a/tests/test_db_api.rb +++ b/tests/test_db_api.rb @@ -544,6 +544,20 @@ class DBAPITest < Test::Unit::TestCase assert_equal 1, test.group([], {"a" => {"$gt" => 1}}, {"count" => 0}, "function (obj, prev) { prev.count++; }")[0]["count"] end + def test_deref + @@coll.clear + + assert_equal nil, @@db.dereference(DBRef.new("test", ObjectID.new)) + obj = {"x" => true} + key = @@coll.insert(obj)["_id"] + assert_equal true, @@db.dereference(DBRef.new("test", key))["x"] + + assert_equal nil, @@db.dereference(DBRef.new("test", 4)) + obj = {"_id" => 4} + @@coll.insert(obj) + assert_equal obj, @@db.dereference(DBRef.new("test", 4)) + end + # TODO this test fails with error message "Undefed Before end of object" # That is a database error. The undefined type may go away.