MongoDB가 version 4.0 으로 릴리즈 되면서 생긴 Replica Set에서 작동하는 다중 도큐먼트 트랜잭션
import { startSession } from 'mongoose';
const createCustomersTransaction = async (req, res) => {
const session = await startSession();
try {
await session.withTransaction(async () => {
const options = { session };
// Create customers
await Customer.create({ name: req.body.name }, options);
await Customer.create({ name: req.body.name2 }, options);
});
res.status(200).send('Customers created successfully.');
} catch (error) {
console.error('Transaction aborted. Error:', error);
res.status(500).send('Error creating customers.');
} finally {
session.endSession();
}
};