How to access Mongo Session?


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


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();
// ... etc

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

1 Like

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

1 Like

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();

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.

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