mongodb mongoose事务未按预期运行

xxslljrj  于 2023-02-03  发布在  Go
关注(0)|答案(1)|浏览(164)

我在这段代码中创建了一个mongoose事务。但是它并没有像我预期的那样工作。正如您在这里看到的,我正在通过在事务完成之前抛出一个错误来测试事务。但是,由于某种原因,帐户总是被持久化,而不是回滚事务。为什么

export const signUp = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
     const createdAt = req.body.createdAt ? new Date(req.body.createdAt) : new Date()

     const session = await mongoose.startSession()

     try {
         session.startTransaction()

         const account: IAccount = await Account.create<ICreateAccountInput>({
             createdAt,
             accountName: req.body.accountName,
             accountOwnerName: req.body.accountOwnerName,
             accountOwnerEmail: req.body?.accountOwnerEmail,
             contactName: req.body?.contactName || undefined,
             contactNumber: req.body.contactNumber || undefined,
             contactEmail: req.body.contactEmail || undefined,
         })

         throw new Error('Test error')

         const accountAdmin: IUser = await User.create<ICreateUserInput>({
             createdAt,
             accountId: account._id,
             username: req.body.accountOwnerName,
             email: req.body.accountOwnerEmail,
             role: UserRoles.AccountAdmin,
             password: req.body.password,
             passwordConfirm: req.body.passwordConfirm,
         })

         await session.commitTransaction()

         createSendToken(accountAdmin, 201, res, account)
      } catch (e) {
          session.abortTransaction()
          throw e
      } finally {
          session.endSession()
      }
})
zwghvu4y

zwghvu4y1#

该代码创建会话和事务,但创建的帐户没有使用该会话,因此它不在事务中。
要更正此问题,请将传递给create的对象 Package 在数组中,并将会话选项添加到调用中:

Account.create<ICreateAccountInput>([{
             createdAt,
             accountName: req.body.accountName,
             accountOwnerName: req.body.accountOwnerName,
             accountOwnerEmail: req.body?.accountOwnerEmail,
             contactName: req.body?.contactName || undefined,
             contactNumber: req.body.contactNumber || undefined,
             contactEmail: req.body.contactEmail || undefined,
         }],
         {session: session}
)

相关问题