添加一个字段mongoose发现查询结果

我有这个员工架构在mongoose:

employeesSchema = mongoose.Schema({ id: { type: Number, required: true }, firstName: String, lastName: String, title: String, managerId: { type:Number, required: false }, managerName: { type: String, required: false }, phone: String, mobilePhone: String, email: String, picture: String, }); 

我有我的职能,find员工:

 module.exports.getEmployeeById = function(id, callback){ Employee.find({ {id: id} }, callback); 

}

但是我希望在我的Schema的所有字段旁边有一个结果字段,这个字段是具有managerId:id(该员工以下的员工)的员工的数组。

谢谢

您可以使用$lookuppipe道运算符来实现“自我连接”,并将具有此id的雇员作为其pipe理者(位于名为subordinates的数组中),如下所示:

 module.exports.getEmployeeById = function(id, callback){ Employee.aggregate([ { "$match": { id: id } }, { "$lookup": { "from": "employees", "localField": "id", "foreignField": "managerId", "as": "subordinates" } } ]).exec(callback); }