如何通过关联 Mongoid 4 查找所有文档

How to find all document by association Mongoid 4

我有一个模型 Tag,它可能属于其他几个模型,但目前只有一个模型 Todo 又属于 User,如下所示:

class User
  include Mongoid::Document
  field: name,  type: String
  has_many :todos
end

class Todo
  include Mongoid::Document
  field: name,  type: String
  belongs_to :user
end

class Tag
  include Mongoid::Document
  field: name,  type: String
  belongs_to :todos
end

如何查询属于特定用户的所有 Tags?我写了以下内容:

todo_ids = Todo.where(user_id: '86876876787')

然后:

tags = Tag.where('todo_id.in': todo_ids)

但这些都不起作用。我错过了什么?

您遗漏了两件事:

  1. Mongoid 不是 ActiveRecord,因此它不知道如何处理 Tag 查询中的 todo_ids
  2. 'todo_id.in' 是试图查看 todo_id 散列中的 in 字段的字段路径,这不是 MongoDB 的使用$in 运算符。

您一次只能处理一个集合,因此要修复第一个集合,您需要从 MongoDB:

中提取一组 ID
todo_ids = Todo.where(user_id: '86876876787').pluck(:id)
# -------------------------------------------^^^^^^^^^^^

要修复第二个问题,请使用 $in 运算符:

tags = Tag.where(todo_id: { '$in': todo_ids })
tags = Tag.where(:todo_id.in => todo_ids)
tags = Tag.in(todo_id: todo_ids)
#...