I am not able find the record using Model.find(id).
Food.find('548210e8d5a81037af06b2d6') => Mongoid::Errors::DocumentNotFound
But when I try find the same record using column name , I will return same record.
Food.where({name:"Aloo Matar" }).first
=> #<Food _id: 548210e8d5a81037af06b2d6, rawOrPrepared: "P", name: "Aloo Matar", tags: "vegetable", alternateNames: "potatoes">
For my case, find works differently based on string. Please see the below code.
Food.where({_id: "zyCMnbTPENeXkhawT" })
=> #<Mongoid::Criteria
selector: {"_id"=>"zyCMnbTPENeXkhawT"}
options: {}
class: Food
embedded: false>
2.2.1 :017 > Food.where({_id: '548210e8d5a81037af06b2d6' })
=> #<Mongoid::Criteria
selector: {"_id"=>BSON::ObjectId('548210e8d5a81037af06b2d6')}
options: {}
class: Food
embedded: false>
But first code returns the object while second code raise the exception.
Please help me on this.
Thanks, Hare
Your problem has happened because the document with
_idequal to548210e8d5a81037af06b2d6was saved before you changed your model saying the_idfield should have string type.I suppose you inserted something like the below code onto your model after inserting that document on DB. Right?
So... what is happening with document with id
548210e8d5a81037af06b2d6?Simple. The document was saved with default mongodb
_idtype - which isObjectId.Now (after defining
_idtype as string) whenever you query DB with548210e8d5a81037af06b2d6, it will try to find a document with id equal to548210e8d5a81037af06b2d6but it won't find because it was stored asObjectId('548210e8d5a81037af06b2d6').If you remove
field :_id, type: String, overwrite: truefrom your model, you'll see that the document548210e8d5a81037af06b2d6will be found again, whilestzyCMnbTPENeXkhawTwon't.Thus to solve your problem you have to convert every id on mongodb to the same type.