[英]Mongoid 2.4 Querying For Embedded Document By Id Failing
We have a model Entry with an embedded Item: 我们有一个带有嵌入式项目的模型条目:
class Entry
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Spacial::Document
embeds_many :items, cascade_callbacks: true
...
class Item
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Spacial::Document
embedded_in :entry
...
If i query mongo directly for an entry by item id: 如果我按项目ID直接查询mongo:
{"items._id" : ObjectId("50536b18baa072000f000360")}
It returns the Entry: 它返回条目:
505363b36181ce00020006b1 {"created_at":"2012-09-14T17:04:51Z","items":[{"_id":"50536b1a2b17b3... 505363b36181ce00020006b1 {“created_at”:“2012-09-14T17:04:51Z”,“items”:[{“_ id”:“50536b1a2b17b3 ...
Yet when i query via Mongoid: 然而,当我通过Mongoid查询时:
irb(main):002:0> Entry.where('items._id' => '50536b18baa072000f000360')[0]
=> nil
All other queries work (for other fields on items and for fields on entry). 所有其他查询都有效(对于项目和输入字段的其他字段)。 But not for id. 但不是为了id。
We're running mongoid (2.4.12). 我们正在运行mongoid(2.4.12)。
Apparently you have to wrap the ID in BSON::ObjectId(), so: 显然你必须将ID包装在BSON :: ObjectId()中,所以:
Entry.where('items._id' => BSON::ObjectId('50536b18baa072000f000360'))[0]
Otherwise mongo will sporatically not return the result. 否则mongo将无法返回结果。
This works with Mongoid 4.0.0.beta1: 这适用于Mongoid 4.0.0.beta1:
Entry.where('items._id' => BSON::ObjectId.from_string('50536b18baa072000f000360'))
Here is the link to the documentation. 这是文档的链接。
http://api.mongodb.org/ruby/current/BSON/ObjectId.html#from_string-class_method http://api.mongodb.org/ruby/current/BSON/ObjectId.html#from_string-class_method
Entry.where('items._id' => Moped::BSON::ObjectId('50536b18baa072000f000360'))[0]
请参阅此处的文档
替代方案,这也将起作用。
Entry.find('50536b18baa072000f000360')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.