Home

Published

- 1 min read

transaction rollback mongoose

img of transaction rollback mongoose

The solution for this is noted below

transaction rollback mongoose

Solution

   // Using Mongoose's default connection
const session = await mongoose.startSession()

session.startTransaction() // for starting a new transaction
await session.commitTransaction() // for committing all operations
session.endSession()
await session.abortTransaction() // for rollback the operations
session.endSession()

await Model.create(
	[
		{
			/* payload */
		}
	],
	{ session }
)
await Model.deleteOne(
	{
		/* conditions */
	},
	{ session }
)
await Model.updateOne(
	{
		/* conditions */
	},
	{
		/* payload */
	},
	{ session }
)
await Model.findByIdAndUpdate(
	_id,
	{
		/* payload */
	},
	{ session }
)
const user = new Model(/* payload */)
await user.save({ session })

Try other methods by searching on the site. That is if this doesn’t work