0

I have 3 mongoose schemas Employee, Team and Project. Employee has reference to the team and Team has reference to the Project. Is it possible to get all employees by project Id? I don't want to change schema or use Team model with populate.

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

Below code throws cast error, id is a valid project 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);
  });
});
wisnix
  • 180
  • 1
  • 8

1 Answers1

3

Yes it is possible to get all employees using project Id.but not using single query so you have to modify your function like this

 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);
        });
    });
Dimple Patel
  • 718
  • 1
  • 4
  • 14