Dashiell Rose Bark-Huss
Dashiell Rose Bark-Huss

Reputation: 2965

Mongoose starting and aborting a transaction

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();

Upvotes: 1

Views: 777

Answers (1)

albinjose
albinjose

Reputation: 203

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();

Upvotes: 2

Related Questions