Using Transaction in Mongoose

Kepler·2020년 7월 20일
1

Transactions let you execute multiple operations in isolation and potentially undo all the operations if one of them fails.

Use case: Creating a new document in a collection.

  • import models you defined, as well as startSessionas an object from mongoose. session is an instance of the MongoDB Node.js driver's ClientSession class.
const food = require('../models/food')
const drink = require('../models/drink')

const { startSession } = require('mongoose')
  • startSession() returns a promise that resolves to a classcleintSession , hence use async to get it.
router.get("/food", async (req, res) => {
    const session = await startSession()
  • In your try statement, wrap the codes you want to be excueted as a group between startTransaction() and commitTransaction(), then endSession() to end the session, once it is done.
    try {
        session.startTransaction()

        await food.create([{name:'Tacos'}], {session})
        await drink.create([{name:'Coke'}], {session})

        await session.commitTransaction()
        session.endSession()
        res.send('Success')
  • In your catch statement, instead of commit, use abortTransaction() to undo all the operations.
    } catch (err) {
        await session.abortTransaction()
        session.endSession()
        console.log(err)
        res.send('Error')
    }
})

Note

  • commitTransaction and abortTransaction are both promise objects. Therefore, use await.
  • Any validation tests must be done before the transaction starts to prevent having unfinished transactions due to error.
  • when you use it with create query, wrap your object in an array
profile
🔰

3개의 댓글

comment-user-thumbnail
2021년 1월 5일

It's not working with warning meesage that
"WARNING: to pass a session to Model.create() in Mongoose, you must pass an array as the first argument. See: https://mongoosejs.com/docs/api.html#model_Model.create"

then I change the code.
and I got the error message that
"MongoError: Transaction numbers are only allowed on a replica set member or mongos"

1개의 답글