Transactions let you execute multiple operations in isolation and potentially undo all the operations if one of them fails.
startSession
as 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()
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')
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')
}
})
commitTransaction
and abortTransaction
are both promise objects. Therefore, use await
.create
query, wrap your object in an array
It's not working with warning meesage that
"WARNING: to pass a
session
toModel.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"