0

我有一個MongoDB數據庫,它使用了mongoid referencing according to the documentation。這裏是我的模型:Mongoid:查找引用另一個文檔(引用1-N)

class Mydoc 
    include Mongoid::Document 
    # ... 
    has_and_belongs_to_many :editors, class_name: 'User', inverse_of: nil 
    # ... 
end 

class User 
    # actually, it's based on devise with some changes 
    # ... 
    # it does not reference back to Mydoc, see inverse_of there! 
end 

現在,如果我做給用戶一個參考(授予他/她編輯的角色),mongoid創建一個數組字段名爲editor_ids包含對象ID用戶表中的文檔。工作很好。

我想要查詢顯示某個用戶是編輯器的所有Mydoc文檔。無法弄清楚如何在mongoid中做到這一點。這在mongo控制檯非常簡單:

db.mydocs.find({ editor_ids: { $in: [ ObjectId("52c97e58b878bcf156000001") ] } }) 

它的作用就像魅力。但我需要在軌道中,而不是在控制檯中。基於mongoid文檔,我已經試過這(和地獄很多它的變化),但它不工作:

@docs_where_editor = Mydoc.where(:editors.in => [@user._id]) 

的結果是一個空的數據集。我會很感激任何提示。

我想這不是where方法,因爲在mongoid中,找到只接受要查找的對象id。

回答

1

如果你有一個:editor_ids數組,你只想找一個值,那麼你應該能夠使用正是如此多鍵:

Mydoc.where(:editor_ids => @user.id) 

,如果你有幾個編輯器的ID來搜索,然後:

Mydoc.where(:editors_ids.in => array_of_user_ids) 

將是您的MongoDB控制檯查詢到Mongoid的音譯。

+0

哇,非常感謝。我會發誓說,我已經在很久以前嘗試過類似的東西,但它沒有說在模型中沒有editor_ids這樣的東西。顯然我沒有!再次感謝。 –

相關問題