Transaction in system function of Mongodb Realm app

How to use transactions in the Moongodb Realm app function. If I want to insert 2 documents into 2 collections. If one of them failed the transaction in the session should be rollback. I am talking about the Realm system app function.

1 Like

Hi @Roshan_Prabashana,

As far as I know Realm does not support transactions for now.

What you can potentially do is upload a mongodb node js driver as a dependency and have a code to execute a transaction through the driver.

https://docs.mongodb.com/realm/functions/import-external-dependencies/

Best regards
Pavel

1 Like

The following worked for me

async function main(){
  
    const client  = context.services.get("mongodb-atlas");
    const session = client.startSession();
  
    const coll1 = client.db('TestDb').collection('items');
    const coll2 = client.db('TestDb').collection('items2');
    

 // const session = client.startSession();

   const transactionOptions = {
     readPreference: 'primary',
     readConcern: { level: 'local' },
     writeConcern: { w: 'majority' }
   };
  
  try {
    await session.withTransaction(async () => {
        // Important:: You must pass the session to the operations
    await coll1.insertOne({ name: "abc2" }, { session });
  
     await coll2.insertMany([{ name: "abc2.1" },{ name: "abc1.2" }], { session })
    .then(result => console.log(`Successfully inserted item with _id: ${result.insertedId}`));
    .catch(err => console.error(`Failed to insert item: ${err}`));
      }, transactionOptions);
     } catch (e) {
         console.error(e);
         await session.abortTransaction();
       }
    finally {
       await session.endSession();
      
    }
}
2 Likes

Hi @Roshan_Prabashana,

That’s a new capability, awesome.

https://docs.mongodb.com/realm/mongodb/transactions/

Hope this works to your satisfaction.

Best
Pavel

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.