當我查詢嵌入式模型時,儘管存在大量包含嵌入式模型實例的父記錄,但沒有記錄被返回。Mongoid嵌入式文檔返回空查詢
有兩種模式,嵌入Band
一個Label
:
class Band
include Mongoid::Document
embeds_one :label
end
class Label
include Mongoid::Document
field :name, type: String
embedded_in :band
end
我可以查詢樂隊(Band.all
,Band.find
等)就好了,但是當我查詢標籤,它沒有返回。例如:
創建與嵌入式標籤帶,並將其保存:
> b = Band.create
=> #<Band _id: 516cff525543d8842e000008, _type: nil>
> b.build_label name: "new label"
=> #<Label _id: 516cff5a5543d8842e000009, _type: nil, name: "new label">
> b.save
=> true
然後我查詢了帶模型,所有的罰款:
> Band.all.to_a
=> [#<Band _id: 516cff525543d8842e000008, _type: nil>]
> Band.count
=> 1
> Band.first.label
=> #<Label _id: 516cff5a5543d8842e000009, _type: nil, name: "new label">
> Band.find "516cff525543d8842e000008"
=> #<Band _id: 516cff525543d8842e000008, _type: nil>
但是,當我查詢標籤模型,什麼也沒有顯示!
> Label.all.to_a
=> []
> Label.count
=> 0
> Label.last
=> nil
> Label.first
=> nil
> Label.find "516cff5a5543d8842e000009" # this is the label id from Band
=> nil
我幾乎肯定這不是預期的行爲。代碼直接來自Mongoid文檔的示例:http://mongoid.org/en/mongoid/docs/relations.html#embeds_one
我錯過了什麼?
感謝您的明確解釋。我沒有特定的用例,我只是注意到它,並認爲這是一種奇怪的行爲 - 當你對嵌入式Mongoid模型進行查詢時,Mongoid是否不應該至少發出警告? –
@SherwinYu,你是對的,因爲它是不直觀的,即使它是可以理解的。不幸的是,這是Mongoid的許多(不常見)角落的情況,所以要小心:) –