【问题标题】:Mongoid 2.4 Querying For Embedded Document By Id FailingMongoid 2.4 通过ID查询嵌入文档失败
【发布时间】:2012-09-14 18:51:59
【问题描述】:

我们有一个带有嵌入项目的模型条目:

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

所有其他查询都有效(对于项目的其他字段和条目的字段)。但不是为了身份证。

我们正在运行 mongoid (2.4.12)。

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案1】:

    显然你必须将 ID 包装在 BSON::ObjectId() 中,所以:

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

    否则 mongo 会偶尔不返回结果。

    【讨论】:

    • 或者在我的情况下,Moped::BSON::ObjectId('50536b18baa072000f000360'),为了治愈undefined method `__bson_dump__' for BSON::ObjectId。哇!
    • 在 Mongoid 3 中使用 Moped::BSON::ObjectId
    【解决方案2】:

    这适用于 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

    【讨论】:

      【解决方案3】:

      Entry.where('items._id' => Moped::BSON::ObjectId('50536b18baa072000f000360'))[0] 参见文档here

      【讨论】:

        【解决方案4】:

        或者,这也可以。

        Entry.find('50536b18baa072000f000360')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-07-21
          • 2011-04-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多