How can I create a DBRef according to a given field by myself? For example, I have the UID field in the customer table, and I also have this UID field in the orders table, which will serve to reference the customer that this request belongs to, it’s just not working very well, see:
> db.customers.findOne();
{
"_id" : ObjectId("4ef4a61a90eec3e3c748263c"),
"uid" : 1,
"name" : "Andrey",
"lastname" : "Knupp Vital"
}
> db.orders.findOne();
{
"_id" : ObjectId("4ef4a66490eec3e3c748263d"),
"oid" : 1,
"uid" : 1,
"price" : "149.90"
}
> db.orders.remove();
> order = { oid : 1 , price : 149.90 , uid : new DBRef ( 'customers' , 1 ) } ;
{
"oid" : 1,
"price" : 149.9,
"uid" : {
"$ref" : "customers",
"$id" : 1
}
}
> db.orders.save ( order ) ;
> order.uid.fetch();
null
> order.uid
{ "$ref" : "customers", "$id" : 1 }
>
The DBRef $id value must always be set to the value of the _id field of the referred document. You’re not doing that in your example. Fixed version :