I am trying to have two operations under a transaction.
const instance = new Model(data);
const session = await mongoose.startSession();
await session.withTransaction(async () => {
await Model.updateOne(
filterQuery,
updateQuery,
{ session }
);
instance = await instance.save({ session });
});
await session.endSession();
This part of the code is working fine. But the problem is, I also have a post save hook, which updates some field of the saved instance.
ModelSchema.post('save', (doc, next) => {
const instance = this;
instance.field = updatedValue();
instance.save((err) => {
if (err) log(err);
next();
});
});
The save operation on the hook fails and raises MongoError: Transaction 1 has been committed. I am confused as this operation was not included in the session. Is there any workaround to avoid this error and have the save operation in post save hook?