我在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,
});
我有找到员工的职责:
module.exports.getEmployeeById = function(id, callback){
Employee.find({ {id: id} }, callback);
}
但是我希望在我的Schema的所有字段旁边再添加一个字段,该字段是具有managerId:id(该员工下面的员工)的员工的数组。
由于
答案 0 :(得分:1)
您可以使用 $lookup
管道操作符来自动加入"自我加入"并使用此id
作为其经理(在名为subordinates
的数组中)的员工,如下所示:
module.exports.getEmployeeById = function(id, callback){
Employee.aggregate([
{ "$match": { id: id } },
{
"$lookup": {
"from": "employees",
"localField": "id",
"foreignField": "managerId",
"as": "subordinates"
}
}
]).exec(callback);
}