Mongoose使用多个本地/外键对填充虚拟

时间:2017-04-21 21:02:01

标签: mongoose populate

我刚刚发现了Mongoose的Populate Virtuals方法,它将为我目前的项目节省很多钱。不过,我希望进一步扩展它。是否有一种基于多个本地/外键对填充的简单方法?这是一个代码可能的示例(注意:这可能不是一个很好的例子,但希望它传达了我的问题的基础)。

var workerSchema = new Schema({
    name: String,
    locationCode: String,
    departmentCode: String
});

var deparmentSchema = new Schema({
    locationCode: String,    //Note: neither location nor code
    code: String,            //are unique, but the combination of them are
    manager: String,
    otherInfoAboutDepartment: String
});

workerSchema.virtual('department', {
    ref: "Department",
    localField: ["locationCode", "departmentCode"],
    foreignField: ["locationCode", "code"]
});

1 个答案:

答案 0 :(得分:0)

尽管这可能不是您要找的答案。您可以得到这样的解决方法

workerSchema.virtual('department1',{
   ref: "Department",
   localField: "locationCode",
   foreignField: "locationCode"
})

workerSchema.virtual('department2',{
    ref: "Department",
    localField: "departmentCode",
    foreignField: "code"
})

在查找查询中,您可以使用类似

Worker.find({}).populate('department1').populate('department2')

在处理数据时,您可以检查数据字段是否为空并将两个输出合并为一个