为什么mongo在事务失败的情况下仍保存更改



代码:

const session = await mongoose.startSession();
session.startTransaction();
try {
const model = mongoose.model("cars");
const document = { _id: "6059edf7fc81428fcc0b5c33" };
await model.create(document);
await model.create(document); // illegal duplicate key
await session.commitTransaction();
session.endSession();
} catch (error) {
await session.abortTransaction();
session.endSession();
}

预期行为:我预计整个操作将失败,数据库中没有插入任何条目

实际行为:没有调用commitTransaction((,因为第二个create((失败;调用abortTransaction((,但在执行代码后,数据库会有第一个条目。

这个问题似乎描述了同样的事情,但没有答案:为什么在交易失败的情况下,一些文档会保存在猫鼬交易中

我认为您需要将会话明确地传递给您希望成为会话一部分的每个操作。

以下是文档中的一个示例:

session.startTransaction();
// This `create()` is part of the transaction because of the `session`
// option.
await Customer.create([{ name: 'Test' }], { session: session });

将其应用于您的代码:

const session = await mongoose.startSession();
session.startTransaction();
try {
const model = mongoose.model("cars");
const document = { _id: "6059edf7fc81428fcc0b5c33" };
await model.create(document, {session: session});
await model.create(document, {session: session}); // illegal duplicate key
await session.commitTransaction();
session.endSession();
} catch (error) {
await session.abortTransaction();
session.endSession();
}

最新更新