mongoid找到VS在哪里

bre*_*ter 11 criteria find where mongoid

当我通过ID搜索时,我似乎只对1个特定模型有这个问题

>> 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.
Run Code Online (Sandbox Code Playgroud)

奇怪的是,与其他型号,我可以使用发现就好了.有任何想法吗?

堆栈的其余部分是......

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
Run Code Online (Sandbox Code Playgroud)

ste*_*ard 3

通常问题是相反的。失败的地方和有效的地方。

这是由于在查询之前没有将 id 转换为 BSON::ObjectId 造成的。

通常你必须这样做

Cart.where(:_id => BSON::ObjectId('4dae5902e1607c232c000009')).first
Run Code Online (Sandbox Code Playgroud)

这让我相信你的 id 存储为字符串而不是 BSON:ObjectId 并且可以解释为什么 find 失败(它正在搜索 BSON::ObjectId 而不是字符串)

还可以解释为什么它只是一种模型,因为它完全取决于对象的存储方式。

希望有帮助