0

I am trying to use Mongoose transactions (specifically the form mongoose.connection.transaction, not startTransaction see Connection#transaction() at this location: https://mongoosejs.com/docs/transactions.html).

I have found that if I try to send an Express response inside the transaction it gives the error: Attempted illegal state transition from [TRANSACTION_COMMITTED] to [TRANSACTION_ABORTED]

...so for example, this gives the error:

await mongoose.connection.transaction(async (session) => {

//...a bunch of mongoose stuff here - it doesn't really matter what it is.

res.status(200).json({someObject});

}

...but this works fine:

await mongoose.connection.transaction(async (session) => {

//...a bunch of mongoose stuff here - it doesn't really matter what it is.

}
res.status(200).json({someObject});

Why does the second one work but the first one fail? There's no return statement for the res.send - I can put code after it that executes fine.

Also the DB has the desired resulting state in either case.

...but if I have the response inside the transaction it fails, and outside it works.

Now you may say, "Just take your response out of the transaction." Yes, indeed. ...but I want to understand why!

(Mongoose 7.0.1, Express 4.17.3, Node 16.20.0)

WillyC
  • 3,917
  • 6
  • 35
  • 50

0 Answers0