How to access Mongo Session?


#1

Hi,

Does anyone know how to access Mongo Session in a Meteor method call? I looked at the meteor/mongo object, but it only has methods relating to collections. I also looked at Collection rawDatabase() method, but that didn’t provide it either. The reason I ask is that I want to implement Session.startTransaction() and Session.commitTransaction() to take advantage of transactions feature in Mongo.

Appreciate any advice

Thanks,
Tom


[Solved] Mongo client and session to create a transaction
#2

That’s not directly available from the Meteor Mongo package. However, until it becomes officially available, you could try the following hack:

const client = someCollection._driver.mongo.client;
const session = client.startSession();
session.startTransaction();
// ... etc

Caveat: all that’s untested, but I’m fairly confident :wink:


#3

Nice one - thanks Rob, I’ll give it a whirl :slight_smile:


#4

Hi guys,

You can also access it through the mongo meteor package like this:

import { MongoInternals } from 'meteor/mongo';


const { client } = MongoInternals.defaultRemoteCollectionDriver().mongo;
const session = await client.startSession();

#5

So I did indeed try it just now, but it appears that Mongo transaction doesn’t discard the full transaction if part fails. In my case, I want to insert a Project first, and then insert into a different collection a Workspace with projectId referring to the initially created Project. However, running these two in sequence within a transaction as specified by the Mongo docs, I find that if the Project is successfully inserted, but the Workspace insertion fails, the Project still appears in the collection. Maybe this is somehow due to Meteor’s way of converting everything into synchronous-like code.


#6

From memory these methods return Promises. You should check that and use async/await to ensure things happen in the right order.