Ruby on rails 如何在MongoDB中创建两个文档之间的关系?

Ruby on rails 如何在MongoDB中创建两个文档之间的关系?,ruby-on-rails,mongodb,mongoid,Ruby On Rails,Mongodb,Mongoid,我有一个Ruby on Rails应用程序,它通常通过Mongoidgem与MongoDB通信,但出于性能原因,我需要像这样将文档直接插入MongoDB: Order.collection.insert(Array.new << {order_id: order_id, mail_address: mail_address}) # this creates the document, but does not return anything useful that can be re

我有一个Ruby on Rails应用程序,它通常通过
Mongoid
gem与MongoDB通信,但出于性能原因,我需要像这样将文档直接插入MongoDB:

Order.collection.insert(Array.new << {order_id: order_id, mail_address: mail_address}) # this creates the document, but does not return anything useful that can be referenced: {"n"=>0, "connectionId"=>53675, "wtime"=>0, "err"=>nil, "ok"=>1.0}

Customer.collection.insert(Array.new << {mail_address: mail_address})
Order.collection.insert(Array.new,“connectionId”=>53675,“wtime”=>0,“err”=>nil,“ok”=>1.0}

Customer.collection.insert(Array.newMoped的
insert
方法都没有返回任何对您非常有用的东西,因此您的文档在其
\u id
中获得了正常的ObjectId,但您无法轻松地知道它们是什么。您可以尝试分配自己的
\u id
但不必使用
字符串,您可以n只需说
Moped::BSON::ObjectId.new
即可生成新的
\u id
。假设您的
订单有一个指向
客户的
客户id
,您可以:

customer_id = Moped::BSON::ObjectId.new
Customer.collection.insert(_id: customer_id, mail_address: mail_address)
Order.collection.insert(customer_id: customer_id, ...)

不要害怕使用
mongo
shell查看MongoDB内部的结构。Mongoid提供的所有有用的关系和嵌入便利都很好,但您仍然需要知道它们对您的数据库做了什么。

您的建议是您已经解决了这一问题(至少大部分),你这里还有问题吗?谢谢你深入研究这个问题。你已经是一个活生生的保护程序好几次了。我这里的问题仍然存在。基本上,当我使用上述方法创建对象时,我没有得到
\u id
返回。创建的响应是
{“n”=>0,“connectionId”=>53675,“wtime”=>0,“err”=>nil,“ok”=>1.0}
。因此,当我创建第一个对象时,我不知道如何在创建第二个对象时引用它。解决方法是自己开始设置
\u id
属性(
字段:\u id,type:String,default:->{my\u attribute}
),然后将
my\u attribute
设置为类似于
customer>的字符串_#{mail_address}
订单{order_id}
。然后我会知道要参考的
\u id
。但这感觉像是一个相当丑陋的解决方案。