I'm trying to understand how to begin and undo a transaction. I thought session.abortTransaction()
would cause all the updates in the transaction to undo, in this case, just Profile.updateOne
. But after I ran the code below, Profile
1's username was changed to 'phoebe2'
. Since the transaction was aborted, I'd still expect the username to be the old username.
How do you undo a transaction?
const session = await mongoose.startSession();
await session.startTransaction();
await Profile.updateOne({ _id: '1' }, { username: 'phoebe2' });
// undo transaction
await session.abortTransaction();
await session.endSession();
CodePudding user response:
you need to pass session
as the last argument in updateOne
const session = await mongoose.startSession();
await session.startTransaction();
await Profile.updateOne({ _id: '1' }, { username: 'phoebe2' },{session});
// undo transaction
await session.abortTransaction();
await session.endSession();