如何根据自己的特定字段创建DBRef?例如,我在客户表中有UID字段,我在订单表中也有这个UID字段,用于引用此请求所属的客户,它只是工作得不好,请参阅:
> 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 }
>
答案 0 :(得分:3)
DBRef $ id值必须始终设置为引用文档的_id字段的值。你的例子中没有这样做。修正版:
> 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' , ObjectId("4ef4a61a90eec3e3c748263c") ) } ;
{
"oid" : 1,
"price" : 149.9,
"uid" : {
"$ref" : "customers",
"$id" : ObjectId("4ef4a61a90eec3e3c748263c")
}
}
> db.orders.save(order)
> order.uid.fetch()
{
"_id" : ObjectId("4ef4a61a90eec3e3c748263c"),
"uid" : 1,
"name" : "Andrey",
"lastname" : "Knupp Vital"
}
答案 1 :(得分:2)
我手动完成。拥有额外的标识符字段可能最终导致问题。在您的订单文档中,创建一个'customer_id字段并将其设置为客户的_id。这就像使用关系引用创建SQL外键。我在PHP中这样做:
$customer = $this->mongo->db->customer->findOne(array("name" => $customer_name));
$customer_id = new MongoID($customer['_id']);
$order = Array(
'customer_id' => $customer_id,
...
);
$this->mongo->db->order->insert($order);