问题描述
Federica,Silvio,Enrico
假设我尝试通过数组路径“Cs”删除“指向”多个 ModelC 文档的 ModelA 文档,但在删除之前,我想使用 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);
中间件来遍历每个 ModelC 文档"Cs" 数组并更新它们的 "As" 数组,以便它们不再指向已删除的 ModelC。
pre
在调用 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
});
}
函数之前,a.Cs 是一个 _id 数组。
问题是当我尝试填充“Cs”时 populate
是一个空数组。
这样做的正确方法是什么?
解决方法
确保在填充时调用 exec()
:
const a = await this.model.findOne(this.getQuery()).populate("Cs").exec()