Working with Transactions in Node.js

I have Data Access Objects (DAO) for each collection following

M220JS: MongoDB for JavaScript Developers

online course pattern. I have abstracted complex update/insert queries within each DAO class like the following

Class StudentDAO{
  static async updateCourse(id, data){
     //i) Match query filter
     //ii) Check whether data object contains null values for specified properties
     //iii) Using data retrieved, update relevant document properties
     //iv) Run a utility function for updating specific properties (setting the date dynamically for example)  ​
 ​}
}

For individual queries it runs great, but I now I have to update course along with 2 other collections using payment services. I found Transactions as a great alternative for running payment services in an all or nothing approach, but looking at its docs I am stuck, because for each operation within a transaction, a session shall be passed to each MongoDB query operation like the following (from How to use Transactions in Node.js)

const usersUpdateResults = await usersCollection.updateOne(
                { email: userEmail },
                { $addToSet: { reservations: reservation } },
                { session });

The problem I am facing, that I have 4 operations in an individual payment service, and for each individual operation, I have to check for data checks etc within each specific operation (due to bad database design earlier in another NoSQL database)

My question is that is it possible to pass session to each method in a static class like this

await StudentDAO.updateCourse(userId, data, session);

So that I can simply call these methods using DAO within a transaction and ensure that not only do I have to repeat code (with MongoDB queries instead of abstracting them using DAOS) but also a cluttered and messy codebase that will be hard to maintain should new requirements arise
Thanks.

Managed to do so via sending session object to each DAO function like this

await StudentDAO.updateCourse(userId, data, session);

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