Can you pass mongoose sessions to functions?

Viewed 74

There are some database operations in my codebase that need to occur in multiple API endpoints that require atomicity across multiple collections.

Is it possible to contain these operations in a function and pass the session to the function? Javascript is not passed by reference but I'm thinking if you pass the session object and then return it you should be able to preserve continuity in your main scope. Thinking of implementing code something like this:

let session = await mongoose.startSession();
session = await functionWithDbOperations(session);
//continue implementation

The function would be defined elsewhere:

export const functionWithDbOperations = async (session) => {
    await session.withTransaction(async () => {
        // various db operations
        // more db operations
    });
    return session;
}

Will this result in bugs? I'm not too well versed in Mongodb's implementation of atomicity across multiple DB accesses.

0 Answers
Related