我在这段代码中创建了一个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()
}
})
1条答案
按热度按时间zwghvu4y1#
该代码创建会话和事务,但创建的帐户没有使用该会话,因此它不在事务中。
要更正此问题,请将传递给create的对象 Package 在数组中,并将会话选项添加到调用中: