簡體   English   中英

Mongoose - 會話 abortTransaction 沒有回滾

[英]Mongoose - session abortTransaction is not rolling back

我不知道我錯過了什么,但在塊中捕獲 session.abortTransaction() 沒有滾動任何東西。 我故意在創建用戶后使用 throw new Error("Error message") 登陸 catch 塊以觸發 session.abortTransaction() 但是當我查看數據庫時,我發現盡管流產,用戶仍然被創建.

這是我的源代碼

 export const signUp = async (req, res) => { const { email, password, fullname } = req.body; // Init session const session = await mongoose.startSession(); // Begin transaction session.startTransaction(); try { // Check if user exist in database using his email const dbUser = await UserModel.findOne({ email }, null, session); // Return a conflit code if user already exist if (dbUser) return res.status(409).json({ message: "User already exists" }); // Create tenant const tenantResult = await TenantModel.create([{ createdAt: new Date() }], null, session); // Get admin role const roleResult = await RoleModel.findById('626db17b8645717d657fc4c8', null, session); //Hash password using jwt const hashedPassword = await bcrypt.hash(password, 12); // Store user in db const userResult = await UserModel.create([ { email: email, password: hashedPassword, fullname: fullname, tenant: tenantResult[0], role: roleResult } ], null, session); throw new Error("Error message"); if (userResult){ // Create subscription && currency // Create currency for user await CurrencyModel.create([ { name: 'Dollar', createdAt: new Date(), symbol: '$', isoCode: 'USD', default: true, userRole: 'setting-list', createdBy: userResult[0], } ], null, session); } // Generate token using jwt, secret, and user data const token = jwt.sign( { email: userResult[0].email, id: userResult[0]._id }, secret, { expiresIn: "24h" } ); // Send welcome email to registered user await sendWelcomeEmail(userResult[0].email, userResult[0].fullname, `Welcome ${userResult[0].fullname} - light-speed.dev`, 'welcome-email.html'); //Commit transaction await session.commitTransaction(); // Return 201 Created http code with user and token return res.status(201).json({ userResult, token }); } catch (error) { // Abort transaction if one of these request throw error await session.abortTransaction(); console.log(error); return res.status(400).json({ message: 'Something went wrong!' }); } finally { // close session session.endSession(); } };

謝謝您的幫助!

我終於弄清楚了為什么會話不回滾事務。 這是因為我指定會話選項的方式。

我改變這些行

const dbUser = await UserModel.findOne({ email }).session(session);

const tenantResult = await TenantModel.create([{ createdAt: new Date() }], { session: session });

const roleResult = await RoleModel.findById('626db17b8645717d657fc4c8').session(session);


const userResult = await UserModel.create([
        { 
            email: email, 
            password: hashedPassword, 
            fullname: fullname, 
            tenant: tenantResult[0], 
            role: roleResult 
        }
    ], { session: session });


await CurrencyModel.create([
            {
                name: 'Dollar', 
                createdAt: new Date(),
                symbol: '$', 
                isoCode: 'USD', 
                default: true,
                userRole: 'setting-list',
                createdBy: userResult[0],
            }
        ], { session: session });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM