MongoDB 关于 Mongoid 查询的奇怪问题

cameo · 2013年07月21日 · 最后由 cameo 回复于 2013年09月26日 · 3163 次阅读

我有两个 Model 如下,奇怪的是如果我调用 Community 中的 activities 方法能返回查询结果,如果我直接查询 Activity 则无结果返回。百思不得其解呀!请看下面在 irb 中执行的结果,Mongoid::Criteria 的实例都一模一样!

class Activity
  include Mongoid::Document 
  ....
  field target_object
end
class Community
  include Mongoid::Document
  ....
  def activities
    Activity.where(target_object:{"id" => self.id, "type"=>"Community"})
  end
end

--------------------------------------------------华丽的分割线-------------------------------------- Activity 实例例子

irb(main):002:0> Activity.last
=> #<Activity _id: 51e615b4f9dffbed71000002, _type: nil, created_at: 2013-07-17 03:55:32 UTC, updated_at: 2013-07-17 03:55:32 UTC, verb: :new_article, actor: {"id"=>"51e3661af9dffbce7c000001", "type"=>"User"}, object: {"id"=>"51e615b4f9dffbed71000001", "type"=>"Article"}, target_object: {"id"=>"51e37648f9dffb5e4c000013", "type"=>"Community"}, receivers: [{"id"=>"51e3fb35f9dffbafff000001", "type"=>"User"}]>

执行查询

irb(main):006:0> c = Community.first
=> #<Community _id: 51e37648f9dffb5e4c000013, _type: nil, created_at: 2013-07-15 04:10:48 UTC, updated_at: 2013-07-15 14:15:05 UTC, name: "Biboo World", brief: "精彩水世界", user_ids: ["51e3661af9dffbce7c000001", "51e3fb35f9dffbafff000001"]>
irb(main):007:0> c.activities
=> #<Mongoid::Criteria
  selector: {"target_object"=>{"id"=>"51e37648f9dffb5e4c000013", "type"=>"Community"}}
  options:  {}
  class:    Activity
  embedded: false>

irb(main):008:0> c.activities.count
=> 11


irb(main):015:0> Activity.where(target_object: {"id"=>"51e37648f9dffb5e4c000013", "type"=>"Community"})
=> #<Mongoid::Criteria
  selector: {"target_object"=>{"id"=>"51e37648f9dffb5e4c000013", "type"=>"Community"}}
  options:  {}
  class:    Activity
  embedded: false>

irb(main):014:0>  Activity.where(target_object: {"id"=>"51e37648f9dffb5e4c000013", "type"=>"Community"}).count
=> 0

self.id 本来就不是 string 类型……这两个查询只是看起来是一样的而已……

#1 楼 @aptx4869 一语种的呀!!!

你的 Activity 对象的 target_obj 存的是 { "id" => ObjectID("xxxx"), "type" => "Commmunity" }的数据,因此,你在代码中查询的时候,你传入的 hash 中的 id 字段是 object_id 对象,但是你直接查询的时候,"id" 就是 string 对象,不匹配的

需要 登录 后方可回复, 如果你还没有账号请 注册新账号