【问题标题】:Mongoose filter by nested reference嵌套引用的猫鼬过滤器
【发布时间】:2020-11-05 11:06:30
【问题描述】:

我有 3 个猫鼬模式 Employee、Team 和 Project。员工引用了团队,团队引用了项目。是否可以通过项目 ID 获取所有员工?我不想更改架构或使用 Team 模型进行填充。

const employeeSchema = mongoose.Schema({
  email: { type: String, required: true, unique: true },
  team: { type: mongoose.Schema.Types.ObjectId, ref: "Team" },
});

const teamSchema = mongoose.Schema({
  name: { type: String, required: true },
  employees: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
  project: { type: mongoose.Schema.Types.ObjectId, ref: "Project" },
});

以下代码抛出转换错误,id 是有效的项目 id。

router.get("/:id/employees", checkAuth, (req, res, next) => {
  const id = req.params.id;
  console.log(id);
  Employee.find({ team:{project:id}}).then((employees) => {
    console.log(employees);
  });
});

【问题讨论】:

  • 项目的架构是什么样的?它是否引用了用户?
  • Refer这可能会帮助您解决问题

标签: javascript node.js mongoose


【解决方案1】:

是的,可以使用项目 ID 获取所有员工。但不能使用单个查询,因此您必须像这样修改函数

 const id = mongoose.Types.ObjectId(req.params.id);
    Team.findOne({ project: id }, { _id: 1 }, function (err, docs) {
        // Get the Team which match with project ID
        Employee.find({ team: docs._id }, function (err, docs1) {
            //Get all employee belongs to that team and project
            console.log(docs1);
        });
    });

【讨论】:

  • 我试图避免这种方式,但还是感谢您的回答。
猜你喜欢
  • 2021-11-07
  • 2018-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-27
  • 2021-03-23
  • 2020-06-04
  • 2019-03-22
相关资源
最近更新 更多