rails mongoid查找文件

发布于 2025-01-18 03:33:45 字数 667 浏览 3 评论 0原文

当我在Rails Console中执行时:

User.first
 => #<User _id: 6241f97de64d1eb2cc003d08,.... 

我会收到文档,但是当我尝试通过ID找到它时

。find('6241f97de64d1eb2cc003d08')或user.find(bson :: objectid('6241f97de64de64de64d1eb2cc003d08'')或 user.find('6241f97de64d1eb2cc003d08'.to_bson)等

我得到:

message:                                                                          
  Document(s) not found for class User with id(s) 6241f97de64d1eb2cc003d08.   

为什么

3.0.3 :049 > User.where(_id: BSON::ObjectId('6241f97de64d1eb2cc003d08')).find
 => nil 

它不起作用?

我使用Rails 7和Mongoid

When I do in rails console:

User.first
 => #<User _id: 6241f97de64d1eb2cc003d08,.... 

I get document, but when I try to find it by id like

User.find('6241f97de64d1eb2cc003d08') or User.find(BSON::ObjectId('6241f97de64d1eb2cc003d08')) or
User.find('6241f97de64d1eb2cc003d08'.to_bson) etc

I get:

message:                                                                          
  Document(s) not found for class User with id(s) 6241f97de64d1eb2cc003d08.   

also

3.0.3 :049 > User.where(_id: BSON::ObjectId('6241f97de64d1eb2cc003d08')).find
 => nil 

Why it does not work????

I use rails 7 and mongoid

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷月断魂刀 2025-01-25 03:33:45

终于找到了解决方案。

用户模型被这样定义:

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  field :_id, type: String
  field :first_name, type: String
  field :last_name, type: String
end

并将其更改为此:

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  # field :_id, type: String
  field :first_name, type: String
  field :last_name, type: String
end

评论“字段:_id”可以做到这一点。我认为字符串类型是“覆盖”预期的objectid,因为_id和查找方法正在将字符串转换为ObjectID,因此我们最终以搜索字符串与objectID进行了搜索。

Finally found the solution.

User model was defined like this:

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  field :_id, type: String
  field :first_name, type: String
  field :last_name, type: String
end

And changing it to this:

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  # field :_id, type: String
  field :first_name, type: String
  field :last_name, type: String
end

Commenting "field: _id" did the trick. I think string type was "covering" expected ObjectId as _id and find methods are converting strings into ObjectId so we ended up in search against string vs ObjectId.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文