node.jsmongoosepassport-local-mongoose

Use mongoose transaction with passport-local-mongoose


I'm currently working on a project where I need to create two documents for new users in Mongoose. One of these documents contains the user's account information, i.e. username and hash, the other document contains further data. The user's account information is created using passport-local-mongoose.

Since either document creation process could fail, I want to use Mongoose transactions to be able to roll back. Is there a way to use transactions with passport-local-mongoose?

I was imagining something like this, but unfortunately it doesn't work.

const session = await db.startSession()
session.startTransaction()

try {
    await User.register(
        new User({...}), req.body.password, function(err, msg) {...},
        { session: session }
    )

    // Create second document here

    await session.commitTransaction()
    session.endSession()
}
catch(err) {
    await session.abortTransaction()
    session.endSession()
}

Solution

  • I figured out how to do it. I had to register the user a different way than by using the register function.

    const session = await db.startSession()
    session.startTransaction()
    
    try {
        const newUser = new User({...})
        await newUser.setPassword(req.body.password)
        await newUser.save({ session: session })
    
        await session.commitTransaction()
        session.endSession()
    }
    catch(err) { ... }