简体   繁体   中英

mogoose transaction is not working with MongoDB

Code

router.get("/", async (req, res) => {
  const sesion = await mongoose.startSession();

  try {
    sesion.startTransaction();
    const blog = new Blog({ title: "blog title" });
    const byte = new Dsabytes({ topStory: "Not an ObjectId" });
    await blog.save();
    await byte.save(); // throw an error, because topStory should be an ObjectId

    await sesion.commitTransaction();
    sesion.endSession();
    res.send("OK");
  } catch (e) {
    console.log(e);
    await sesion.abortTransaction();
    sesion.endSession();
    res.status(500).send(e.toString());
  }
});

In the Dsabytes schema,I have defined topStory to be an ObjectId . When I run the above code with topStory:"6167213f5003f3d062dd833f" then it's working fine.

But, when await byte.save() throws an error then ideally sesion.abortTransaction() should remove the update caused by blog.save() .

Database before API call

Blogs

[]

Dsabytes

[]

DB after API call

Blogs

[
{
  title:"blog title"
}
]

Dsabytes

[]

So, when it throws an error then both collections should be empty at the end?

I think you'll have to pass the session on save

something like that

await blog.save({ session });
await byte.save({ session });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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