Reputation: 51
I am new to MongoDB. I am trying to learn Transactions. I am trying to add a record inside a transaction. I am throwing an error inside transaction. Here is my code
await client.connect()
console.table('.....connected');
const session = client.startSession()
console.log('...session started');
await session.withTransaction(async () => {
console.log('.....Promise started')
const db: Db = client.db('sample_mflix')
movieCollection = db.collection('movies');
movieCollection.insertOne({ abc: 11 })
new Error('error occured')
then((res) => {
console.log('.....inserted')
}).catch(err => {
console.log('...error', err);
}).finally(async () => {
console.log('...session ended')
session.endSession()
})
But even on error throwing record is being saved in database. But it should not. What shall I do make my transaction ACID.
Upvotes: 1
Views: 546
Reputation: 1599
You are not using the created sessions to do write operations. Instead of
movieCollection = db.collection('movies');
Try
movieCollection = session.getDatabase("'sample_mflix'").movies;
Then you have to start the transaction and write data
session.startTransaction();
movieCollection.insertOne({ abc: 11 });
This should now rollback the changes committed, when you call endSession()
as it would trigger to abort any open transactions.
Also see: https://docs.mongodb.com/manual/reference/method/Session/ and https://docs.mongodb.com/manual/core/transactions/
Upvotes: 2