Connection.prototype.startSession()

Parameters
  • [options] «Object» see the mongodb driver options

  • [options.causalConsistency=true] «Boolean» set to false to disable causal consistency

  • [callback] «Function»

Returns:
  • «Promise<ClientSession>» promise that resolves to a MongoDB driver ClientSession

Requires MongoDB >= 3.6.0. Starts a MongoDB session for benefits like causal consistency, retryable writes, and transactions.

Example:

  1. const session = await conn.startSession();
  2. let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
  3. await doc.remove();
  4. // `doc` will always be null, even if reading from a replica set
  5. // secondary. Without causal consistency, it is possible to
  6. // get a doc back from the below query if the query reads from a
  7. // secondary that is experiencing replication lag.
  8. doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });