Mongoid:数据选择错误

时间:2012-07-26 11:46:00

标签: ruby-on-rails ruby-on-rails-3 mongodb exception-handling mongoid

我在mongodb数据库中使用了带有mongoid gem的rails3.2.3。我有以下代码
user = User.find_by(username: login)
但是当发布的用户名与任何文档的用户名不匹配时,此代码会出错。错误是这样的:
Problem:
Document(s) not found for class User with id(s) 5010cdc81d41c8d30b0000405. Summary: When calling User.find with an id or array of ids, each parameter must match a document in the database or this error will be raised. The search was for the id(s): 5010cdc81d41c8d30b0000405 ... (1 total) and the following ids were not found: 5010cdc81d41c8d30b0000405. Resolution: Search for an id that is in the database or set the Mongoid.raise_not_found_error configuration option to false, which will cause a nil to be returned instead of raising this error when searching for a single id, or only the matched documents when searching for multiples.


我不知道要解决这个问题。请帮我。提前谢谢。

1 个答案:

答案 0 :(得分:0)

此用途为user = User.find_or_create_by(username: login)
而不是user = User.find_by(username: login)