Why mongoose abortTransaction() not working?

Viewed 1063
  • MacOS: 10.15.5
  • NodeJS: 10.16.3
  • Mongoose: 5.8, 5.9
  • MongoDB: 4.0.3

I have next code:

import User from 'models/user'

const session = await User.startSession()
session.startTransaction()

try{
  const user = await User.findOne({ email: 'test@test.com' })
  user.email = 'test111@test111.com'
  await user.save()
  
  throw
}
catch(e){
  await session.abortTransaction()
}
finally{
  await session.endSession()
}

But in database I see:

"email": "test111@test111.com'"

Why abortTransaction() does not working as expected? What I'm doing wrong?

1 Answers

Pass the session to the DB methods involved in the transaction:

 const user = await User.findOne({ email: 'test@test.com' }, null, { session })
 user.email = 'test111@test111.com'
 await user.save({ session })
Related