Mongoid 查询不在新模型字段上返回任何内容

Mongoid queries not returning anything on new model fields

我有一个 Rails 应用程序,我试图根据对象是否已存档来迭代模型 class 中的每个对象。

class Model
  include Mongoid::Document
  include Mongoid::Timestamps

  field :example_id, type: Integer
  field :archived, type: Boolean, default: false

  def archive_all
    Model.all.where(archived: false).each do |m|
      m.archive!
    end
  end

end

但是,where 子句没有返回任何内容。当我进入控制台并输入这些行时,这是我得到的:

Model.where(example_id: 3).count   #=> 23
Model.where(archived: false).count #=> 0
Model.all.map(&:archived) #=> [false, false, false, ...]

我在整个应用程序中还有其他 where 子句,它们似乎工作正常。如果有任何区别,'archived' 字段是我最近添加的字段。

这里发生了什么?我做错了什么?

当你说:

Model.where(archived: false)

您正在 MongoDB 中查找文档 archived 字段恰好是 false。如果您刚刚添加了 archived 字段,那么数据库中的 none 文档将具有该字段(不,:default 无关紧要),因此不会有任何与archived: false。您最好查找 archived 不是 true:

的文档
Model.where(:archived.ne => true).each(&:archive!)

您可能想要在 archived 上添加验证以确保它始终是 truefalse 并且每个文档都有该字段。