Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoid find VS where

i seem to only be having this issue with 1 particular model when i am searching by ID

>> Cart.where(:_id => '4dae5902e1607c232c000009').first
=> #<Cart _id: 4dae5902e1607c232c000009, _id: BSON::ObjectId('4dae5902e1607c232c000009'), _type: nil>
>> Cart.find('4dae5902e1607c232c000009')
Mongoid::Errors::DocumentNotFound: Document not found for class Cart with id(s) 4dae5902e1607c232c000009.

the strange thing is that with other models, i can use find just fine. any ideas?

the rest of the stack is...

from /Library/Ruby/Gems/1.8/gems/mongoid-2.0.1/lib/mongoid/criterion/inclusion.rb:192:in `execute_or_raise'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.0.1/lib/mongoid/criterion/inclusion.rb:190:in `tap'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.0.1/lib/mongoid/criterion/inclusion.rb:190:in `execute_or_raise'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.0.1/lib/mongoid/criterion/inclusion.rb:106:in `find'
from /Library/Ruby/Gems/1.8/gems/mongoid-2.0.1/lib/mongoid/finders.rb:67:in `find'
from (irb):37
like image 345
brewster Avatar asked Apr 20 '11 04:04

brewster


Video Answer


1 Answers

Normally the issue is the other way around. With the where failing and the find working.

That is cause by where not casting the id into BSON::ObjectId before the query.

Usually you would have to do this

Cart.where(:_id => BSON::ObjectId('4dae5902e1607c232c000009')).first

This leads me to believe that your ids are stored as strings and not BSON:ObjectId and would explain why find fails ( it is searching for a BSON::ObjectId not a string)

Could also explain why it is only one model as it depends entirely on how the objects are stored.

Hope that helps

like image 108
stellard Avatar answered Oct 04 '22 20:10

stellard