簡體   English   中英

Mongoid 2.4通過Id失敗查詢嵌入式文檔

[英]Mongoid 2.4 Querying For Embedded Document By Id Failing

我們有一個帶有嵌入式項目的模型條目:

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
...

如果我按項目ID直接查詢mongo:

{"items._id" : ObjectId("50536b18baa072000f000360")}

它返回條目:

505363b36181ce00020006b1 {“created_at”:“2012-09-14T17:04:51Z”,“items”:[{“_ id”:“50536b1a2b17b3 ...

然而,當我通過Mongoid查詢時:

irb(main):002:0> Entry.where('items._id' => '50536b18baa072000f000360')[0]
=> nil

所有其他查詢都有效(對於項目和輸入字段的其他字段)。 但不是為了id。

我們正在運行mongoid(2.4.12)。

顯然你必須將ID包裝在BSON :: ObjectId()中,所以:

Entry.where('items._id' => BSON::ObjectId('50536b18baa072000f000360'))[0]

否則mongo將無法返回結果。

這適用於Mongoid 4.0.0.beta1:

Entry.where('items._id' => BSON::ObjectId.from_string('50536b18baa072000f000360'))

這是文檔的鏈接。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM