2011-03-14 113 views
0

品牌新的MongoDB/mongoid和上的Ruby/Rails還是蠻綠色mongoid查詢軌3

軌控制檯上:

t = Task.all(:conditions => {:title => "task2"}) 

=> #<Mongoid::Criteria 
selector: {:title=>"task2"}, 
options: {}, 
class: Task, 
embedded: false> 


>> t.first 
=> #<Task _id: 4d7e2cdb73ec3227dd000009, title: "task2", latitude: 23.987904829, longitude: -12.9423875, created_by: "4d792d6973ec3248e3000001"> 

回報什麼,我所期望的,但

t = Task.where(:created_by => "4d792d6973ec3248e3000001") 

=> #<Mongoid::Criteria 
selector: {:created_by=>BSON::ObjectId('4d792d6973ec3248e3000001')}, 
options: {}, 
class: Task, 
embedded: false> 

>> t.first 
=> nil 

相同結果如下:

t = Task.all(:conditions => {:created_by => "4d792d6973ec3248e3000001"}) 

這裏是模型:

class Task 
    include Mongoid::Document 
    field :title 
    field :latitude,     :type => Float 
    field :longitude,     :type => Float 
    field :created_by 
end 

我究竟做錯了什麼?

更新例如:

>> Task.new(:title => "task8", :created_by => "4d792d6973ec3248e3000001") 
=> #<Task _id: 4d81037973ec32cc22000003, latitude: nil, longitude: nil, title: "task8", created_by: "4d792d6973ec3248e3000001"> 

>> t = Task.all(:conditions => {:created_by => "4d792d6973ec3248e3000001"}) 
=> #<Mongoid::Criteria 
selector: {:created_by=>BSON::ObjectId('4d792d6973ec3248e3000001')}, 
options: {}, 
class: Task, 
embedded: false> 

>> t.first 
=> nil 

我需要特別限定CREATED_BY爲:類型=>字符串?

+1

什麼問題? – Elxx 2011-03-14 23:52:13

+0

我試圖根據created_by字段執行查詢。不知道我做錯了什麼。 – sysconfig 2011-03-15 01:41:45

+0

你可能在用ObjectIds和匹配來解決一個問題。 mongoid文檔對匹配ObjectIds有什麼看法? – 2011-03-15 21:24:24

回答

1

看起來像created_by是作爲字符串存儲在您的文檔中,但然後您查詢查找ObjectId。 ObjectId和字符串不一樣。

嘗試改變

>> Task.new(:title => "task8", :created_by => "4d792d6973ec3248e3000001") 

>> Task.new(:title => "task8", :created_by => BSON::ObjectId("4d792d6973ec3248e3000001")) 
+0

更新了新的例子..我需要專門設置類型? – sysconfig 2011-03-16 18:46:21

+0

沒有專門設置類型,所以看起來像mongo是「假設」我的意思是對象ID。最終創建了一個參考協會來解決它。 – sysconfig 2011-03-22 11:42:44

0

你必須包括在本mongoid功能在docs解釋說:

class Person 
    include Mongoid::Document 
    include Mongoid::Timestamps 
end