【问题标题】:Why is mongo saving changes even though the transaction fails?为什么即使事务失败,mongo 也会保存更改?
【发布时间】:2021-06-20 04:45:01
【问题描述】:

代码:

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(),但代码执行后,数据库有第一个条目。

似乎这个问题描述了同样的事情,但没有答案: Why does some documents get saved in mongoose transactions eventhough the transaction fails

【问题讨论】:

    标签: mongodb mongoose transactions


    【解决方案1】:

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

    这是来自documentation 的示例:

    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();
    }
    

    【讨论】:

    猜你喜欢
    • 2011-06-14
    • 2013-03-26
    • 2018-12-13
    • 2017-12-06
    • 1970-01-01
    • 2014-11-06
    • 2023-03-20
    • 1970-01-01
    • 2012-08-21
    相关资源
    最近更新 更多