简体   繁体   English

Mongoose - 保持模型与更改相关联

[英]Mongoose - Keep models associated on changes

When I have two Schemas and they refer one another like this:当我有两个 Schema 并且它们像这样相互引用时:

    const SchemaA = new Schema({
        _schemaB: [{
            type: Schema.Types.ObjectId,
            ref: 'SchemaA'
        }]
    });

    const SchemaB = new Schema({
        _schemaA: {
            type: Schema.Types.ObjectId,
            ref: 'SchemaB'
        }
    });

    mongoose.model('SchemaA', SchemaA);
    mongoose.model('SchemaB', SchemaB);

Every time I create a document of the type SchemaB, I need to add it to the collection of SchemaA to keep it updated.每次创建 SchemaB 类型的文档时,我都需要将其添加到 SchemaA 的集合中以保持更新。

To achieve it, I'm using a pre.save(...) hook in the SchemaB, but I was wondering if there is a better way to do it.为了实现它,我在pre.save(...)使用了pre.save(...)钩子,但我想知道是否有更好的方法来做到这一点。

Thank you!谢谢!

The only issue I see with using pre hook is what will happen if pre hook succeeds and then actual save fails.我在使用 pre hook 时看到的唯一问题是如果 pre hook 成功然后实际保存失败会发生什么。 In that case you may consider using mongoose transaction to make sure data are saved as one atomic operation.在这种情况下,您可以考虑使用猫鼬事务来确保将数据保存为一个原子操作。

    const session = await SchemaB.startSession();
    session.startTransaction();
    try {
        // save new SchemaB
        // add to SchemA and save SchemaA

        await session.commitTransaction();
        session.endSession();

    } catch (e) {
        await session.abortTransaction();
        session.endSession();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM