Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
Use la sesión de transacción en la función de prueba/captura desde el envoltorio

En múltiples funciones, estoy ejecutando más de una acción de base de datos. Cuando uno de estos falla, quiero revertir las acciones ejecutadas. Por lo tanto, estoy usando una sesión de transacción de Mongoose .

Primero creo una sesión con la función startSession . He agregado la sesión a las diferentes funciones de Model.create . Al final de la función, me comprometo y finalizo la sesión.

Dado que trabajo con un contenedor asyncHandler en todas mis funciones, no vuelvo a escribir el patrón de prueba/captura dentro de mi función. ¿Hay alguna manera de llevar la sesión al asyncHandler de un contenedor diferente para cancelar la transacción cuando una o más de estas funciones fallan?

Ejemplo de función de registro

 import { startSession } from 'mongoose'; import Company from '../models/Company'; import Person from '../models/Person'; import User from '../models/User'; import Mandate from '../models/Mandate'; import asyncHandler from '../middleware/asyncHandler'; export const register = asyncHandler(async (req, res, next) => { const session = await startSession(); let entity; if(req.body.profile_type === 'company') { entity = await Company.create([{ ...req.body }], { session }); } else { entity = await Person.create([{ ...req.body }], { session }); } // Create user const user = await User.create([{ entity, ...req.body }], { session }); // Create mandate await Mandate.create([{ entity, status: 'unsigned' }], { session }); // Generate user account verification token const verification_token = user.generateVerificationToken(); // Send verification mail await sendAccountVerificationMail(user.email, user.first_name, user.language, verification_token); await session.commitTransaction(); session.endSession(); res.json({ message: 'User succesfully registered. Check your mailbox to verify your account and continue the onboarding.', }) });

ayudante de asyncHandler

 const asyncHandler = fn => ( req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); export default asyncHandler;
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!