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

5ktev3wc  于 2022-11-13  发布在  Go
关注(0)|答案(2)|浏览(202)

我刚刚发现了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"]
});
pcww981p

pcww981p1#

虽然这可能不是您要寻找的答案。

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

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

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

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

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

f5emj3cl

f5emj3cl2#

您可以使用Mongoose 5.5中引入的match函数,请参阅此处
它向Mongoose用于populate()的查询添加了一个额外的过滤条件

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

const departmentSchema = 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: "departmentCode",
  // It will reference to departmentCode -> code in Department 
  foreignField: "code",
  //We can use the match option to filter the results based on the
  //parent document. In this case, we only want to return the
  //department if the locationCode matches the parent document's locationCode.
  match: (doc) => ({ locationCode: doc.locationCode }),
});

相关问题