Mongoose 使用多个本地/外来密钥对填充虚拟机

Jus*_*tin 5 populate mongoose

我刚刚发现了 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"]
});
Run Code Online (Sandbox Code Playgroud)

小智 0

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

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

workerSchema.virtual('department2',{
    ref: "Department",
    localField: "departmentCode",
    foreignField: "code"
})
Run Code Online (Sandbox Code Playgroud)

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

Worker.find({}).populate('department1').populate('department2')
Run Code Online (Sandbox Code Playgroud)

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