When I try to use DBRef in the mongo ruby driver (creating a new DBRef object and including in a document which I am inserting into a collection), I get this error that I cannot make heads nor tails of:
NoMethodError (undefined method `bson_type' for #<Mongo::DBRef:0x0056466ed55e48>):
app/controllers/payment_notifications_controller.rb:43:in `block in create'
app/controllers/payment_notifications_controller.rb:19:in `create'
Here is the code in question:
user_mongo = Urgent::Application.config.mongo_client[:user].find(uuid: order.identity.uuid)
if user_mongo
grant_document = { :target => Mongo::DBRef.new("user", user_mongo.first["_id"]), :role => order_item.expirable.backend_id, :created => Time.now, :store_item_id => order_item.id, :store_order_id => order.id }
if expires
grant_document[:expires] = expires
end
Urgent::Application.config.mongo_client[:grant].insert_one(grant_document)
end
Line 39 refers to the second to last line in the code snippet.
The Ruby Mongo driver (I am using v2.2.0) does not define a bson_type
method on the Mongo::DBRef
class. I was able to work around this particular limitation by specifying the DB reference as extended JSON (link). Define your grant_document
hash as:
grant_document = { :target => { "$ref" => "user", "$id" => user_mongo.first["_id"] }, :role => ... }