LMH
LMH

Reputation: 949

Mongoid 2.4 Querying For Embedded Document By Id Failing

We have a model Entry with an embedded Item:

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
...

If i query mongo directly for an entry by item id:

{"items._id" : ObjectId("50536b18baa072000f000360")}

It returns the Entry:

505363b36181ce00020006b1 {"created_at":"2012-09-14T17:04:51Z","items":[{"_id":"50536b1a2b17b3...

Yet when i query via Mongoid:

irb(main):002:0> Entry.where('items._id' => '50536b18baa072000f000360')[0]
=> nil

All other queries work (for other fields on items and for fields on entry). But not for id.

We're running mongoid (2.4.12).

Upvotes: 10

Views: 4435

Answers (4)

Som Poddar
Som Poddar

Reputation: 1451

Alternative, this will also work.

Entry.find('50536b18baa072000f000360')

Upvotes: -3

user3368559
user3368559

Reputation: 51

This works with Mongoid 4.0.0.beta1:

Entry.where('items._id' => BSON::ObjectId.from_string('50536b18baa072000f000360'))

Here is the link to the documentation.

http://api.mongodb.org/ruby/current/BSON/ObjectId.html#from_string-class_method

Upvotes: 5

amit_saxena
amit_saxena

Reputation: 7614

Entry.where('items._id' => Moped::BSON::ObjectId('50536b18baa072000f000360'))[0] see the documentation here

Upvotes: 0

LMH
LMH

Reputation: 949

Apparently you have to wrap the ID in BSON::ObjectId(), so:

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

Otherwise mongo will sporatically not return the result.

Upvotes: 19

Related Questions