【发布时间】:2021-06-03 05:37:43
【问题描述】:
const schemaA = new mongoose.Schema({
Cs: [{type: mongoose.Schema.Types.ObjectId, ref: "ModelC"}]
});
const ModelA = mongoose.model("ModelA", schemaA);
const schemaB = new mongoose.Schema({
Cs: [schemaC]
});
const ModelB = mongoose.model("ModelB", schemaB);
const schemaC = new mongoose.Schema({
name: String,
As: [{type: mongoose.Schema.Types.ObjectId, ref: "ModelA"}]
});
const ModelC = mongoose.model("ModelC", schemaC);
假设我尝试删除通过数组路径“Cs”“指向”多个 ModelC 文档的 ModelA 文档,但在删除之前,我想使用 pre 中间件来遍历每个 ModelC 文档"Cs" 数组并更新它们的 "As" 数组,使它们不再指向已删除的 ModelC。
schemaA.pre("remove", { query: true, document: false }, async function (next) {
const a = await this.model
.findOne(this.getQuery())
.populate("Cs");
a.Cs.forEach((c) => {
// Update each `c.As` to no longer have a ref to the removed ModelA
// Problem is a.Cs is an empty MongooseArray
});
}
在调用populate 函数之前,a.Cs 是一个_ids 数组。
问题是当我尝试填充“Cs”时,a.Cs 是一个空数组。
这样做的正确方法是什么?
【问题讨论】:
标签: node.js mongodb mongoose mongoose-schema mongoose-populate