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

225
Views
mangosta cómo enviar transacciones múltiples colecciones

Nota al margen Me conecto a DB con el siguiente código:

 const mongoose = require('mongoose'); const connectDB = (url) => { return mongoose.connect(url); }

Descripción del problema: Tengo dos colecciones diferentes. Ambas operaciones, findByIdAndUpdate y create deben ejecutarse como una operación atómica. Esto debería ser posible con Transacciones mangosta.

 const registerCustomer = async (req, res) => { await CustomerRegistrationCode.findByIdAndUpdate(req.body._id, { used: true }); const customer = await Customer.create({firstName: req.body.firstName}); }

Lo que probé:

 const registerCustomer = async (req, res) => { const session = await mongoose.startSession(); await session.startTransaction(); try { await CustomerRegistrationCode.findByIdAndUpdate(req.body._id, { used: true }); //updates even though const customer = await Customer.create({ firstName: req.body.firstName });// this line will throw error await session.commitTransaction(); session.endSession(); } catch (error) { console.error('abort transaction'); await session.abortTransaction(); session.endSession(); throw error; } }

Problema La colección CustomerRegistrationCode se actualiza aunque el método Customer.create genera un error. ¿Cómo se puede solucionar esto?

El nuevo enfoque para comprender las transacciones de MongoDB falla, pero este es un código oficial de https://mongoosejs.com/docs/transactions.html

 const mongoose = require('mongoose'); const debugMongo = async () => { const db = await mongoose.createConnection("mongodb://localhost:27017/mongotest"); const Customer = db.model('Customer', new mongoose.Schema({ name: String })); const session = await db.startSession(); session.startTransaction(); await Customer.create([{ name: 'Test' }], { session: session }); //(node:20416) UnhandledPromiseRejectionWarning: MongoServerError: Transaction numbers are only allowed on a replica set member or mongos let doc = await Customer.findOne({ name: 'Test' }); assert.ok(!doc); doc = await Customer.findOne({ name: 'Test' }).session(session); assert.ok(doc); await session.commitTransaction(); doc = await Customer.findOne({ name: 'Test' }); assert.ok(doc); session.endSession(); } debugMongo();

En Customer.create se lanza un error y no sé por qué. ¿Alguien tiene un ejemplo mínimo de trabajo?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Estás usando la transacción de forma incorrecta, por eso no funciona.

Debe pasar el objeto de session a sus operaciones.

 const registerCustomer = async (req, res) => { const session = await mongoose.startSession(); session.startTransaction(); try { await CustomerRegistrationCode.findByIdAndUpdate(req.body._id, { used: true }, { session }); const customer = await Customer.create({ firstName: req.body.firstName }, { session }); await session.commitTransaction(); } catch (error) { console.error('abort transaction'); await session.abortTransaction(); } finally { session.endSession(); } }

Además, he refactorizado un poco tu código.

Puedes leer más sobre transacciones aquí

about 4 years ago · Juan Pablo Isaza Report
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!