首页 > 解决方案 > 嵌套引用的猫鼬过滤器

问题描述

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

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);
  });
});

标签: javascriptnode.jsmongoose

解决方案


是的,可以让所有员工使用项目 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);
        });
    });

推荐阅读