【问题标题】:Mongoose | populate an array of ref documents of a collection that is also an embedded collection of another collection猫鼬 |填充集合的引用文档数组,该集合也是另一个集合的嵌入式集合
【发布时间】: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


    【解决方案1】:

    填充时请务必调用exec()

    const a = await this.model.findOne(this.getQuery()).populate("Cs").exec()
    

    【讨论】:

    • 不幸的是,这并没有什么不同。
    猜你喜欢
    • 1970-01-01
    • 2022-08-08
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-26
    • 2019-08-07
    • 1970-01-01
    相关资源
    最近更新 更多