Use MongoDB Transactions in migration scripts
masterTo use the MongoDB Transaction API, you must be using MongoDB 4.0+ and migrate-mongo 7.0.0+.
migrate-mongo passes a client argument (an instance of MongoClient) as the second argument to your up and down functions. You can use this client to call startSession() and wrap your operations in withTransaction().
module.exports = {
async up(db, client) {
const session = client.startSession();
try {
await session.withTransaction(async () => {
await db.collection('albums').updateOne({artist: 'The Beatles'}, {$set: {blacklisted: true}}, {session});
await db.collection('albums').updateOne({artist: 'The Doors'}, {$set: {stars: 5}}, {session});
});
} finally {
await session.endSession();
}
},
async down(db, client) {
const session = client.startSession();
try {
await session.withTransaction(async () => {
await db.collection('albums').updateOne({artist: 'The Beatles'}, {$set: {blacklisted: false}}, {session});
await db.collection('albums').updateOne({artist: 'The Doors'}, {$set: {stars: 0}}, {session});
});
} finally {
await session.endSession();
}
},
};