NoSQL、DBRefs:MongoDB
如何自己根据给定字段创建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 }
>
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 }
>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DBRef $id 值必须始终设置为引用文档的 _id 字段的值。在你的例子中你没有这样做。固定版本:
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 :
我手动做。拥有额外的标识符字段可能最终会导致出现问题。在您的订单文档中,创建“customer_id”字段并将其设置为客户的 _id。这就像使用关系引用创建 SQL 外键。我在 PHP 中这样做:
I do it manually. Having an extra identifier field will likely end up causing problems down the road. In your order documents, create a 'customer_id field and set it to the _id of the customer. It's like create a SQL Foreign Key with the relational reference. I do it in PHP like this: