【问题标题】:mongoid query rails 3mongoid 查询 rails 3
【发布时间】:2011-03-14 23:46:57
【问题描述】:

全新的 MongoDB / mongoid 并且在 ruby​​ / rails 上仍然非常绿色

在 Rails 控制台上:

t = Task.all(:conditions  => {:title => "task2"})

=> #<Mongoid::Criteria
selector: {:title=>"task2"},
options:  {},
class:    Task,
embedded: false>


>> t.first
=> #<Task _id: 4d7e2cdb73ec3227dd000009, title: "task2", latitude: 23.987904829, longitude: -12.9423875,  created_by: "4d792d6973ec3248e3000001">

返回我所期望的,但是

t = Task.where(:created_by => "4d792d6973ec3248e3000001")

=> #<Mongoid::Criteria
selector: {:created_by=>BSON::ObjectId('4d792d6973ec3248e3000001')},
options:  {},
class:    Task,
embedded: false>

>> t.first 
=> nil

结果相同:

t = Task.all(:conditions  => {:created_by => "4d792d6973ec3248e3000001"})

这是模型:

class Task
  include Mongoid::Document
  field :title
  field :latitude,                  :type => Float
  field :longitude,                 :type => Float
  field :created_by
end

我做错了什么?

更新示例:

>> Task.new(:title => "task8", :created_by => "4d792d6973ec3248e3000001")
=> #<Task _id: 4d81037973ec32cc22000003, latitude: nil, longitude: nil, title: "task8", created_by: "4d792d6973ec3248e3000001">

>> t = Task.all(:conditions  => {:created_by => "4d792d6973ec3248e3000001"})
=> #<Mongoid::Criteria
selector: {:created_by=>BSON::ObjectId('4d792d6973ec3248e3000001')},
options:  {},
class:    Task,
embedded: false>

>> t.first 
=> nil

是否需要将 created_by 专门定义为 :type => String ?

【问题讨论】:

  • 我正在尝试基于 created_by 字段执行查询。不知道我做错了什么。
  • 您可能正在与 ObjectIds 和匹配问题作斗争。 mongoid 文档对匹配 ObjectId 有什么看法?

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


【解决方案1】:

看起来 created_by 在您的文档中存储为字符串,但随后您查询以查找 ObjectId。 ObjectId 和字符串不一样。

尝试改变

>> Task.new(:title => "task8", :created_by => "4d792d6973ec3248e3000001")

>> Task.new(:title => "task8", :created_by => BSON::ObjectId("4d792d6973ec3248e3000001"))

【讨论】:

  • 更新了新的例子..我需要专门设置类型吗?
  • 没有专门设置类型,所以看起来 mongo 是“假设”我的意思是对象 ID。最后创建了一个参考关联来解决它。
【解决方案2】:

您必须按照docs 中的说明在 mongoid 中包含此功能:

class Person
  include Mongoid::Document
  include Mongoid::Timestamps
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多