NodeJS 使用带有passport-local-mongoose的mongoose事务

8yoxcaq7  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(106)

我目前正在做一个项目,我需要在Mongoose中为新用户创建两个文档。这些文档中的一个包含用户的帐户信息,即用户名和散列,其他文档包含更多数据。使用passport-local-mongoose创建用户的帐户信息。
由于任何一个文档创建过程都可能失败,所以我希望使用Mongoose事务来回滚。有没有办法使用护照本地 Mongoose 的交易?
我在想象这样的事情,但不幸的是它不起作用。

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()
}
ltskdhd1

ltskdhd11#

我知道怎么做了。我必须以不同于register函数的方式注册用户。

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) { ... }

相关问题