Skip to content
Advertisement

Unable to refer to method `db.start Session ()` in mongoose, mongodb

When I try to refer to db.startSession () I have an error db.startSession () is not a function. In console.log I put db and I put logged variable below. Why can’t I refer to startSession()?

connection

module.exports.db = mongoose
    .createConnection(process.env.DATABASE, { 
        useNewUrlParser: true, 
        useFindAndModify: false,
        useUnifiedTopology: true, 
        useCreateIndex: true
    }
);

controller

const db = require('./connection');

const session = db.startSession();
session.startTransaction();

logged variable db

{
  db: NativeConnection {
    base: Mongoose {
      connections: [Array],
      models: [Object],
      modelSchemas: [Object],
      options: [Object],
      _pluralize: [Function: pluralize],
      plugins: [Array]
    },
    collections: {},
    models: {},
    config: { autoIndex: true },
    replica: false,
    options: null,
    otherDbs: [],
    relatedDbs: {},
    states: [Object: null prototype] {
      '0': 'disconnected',
      '1': 'connected',
      '2': 'connecting',
      '3': 'disconnecting',
      '99': 'uninitialized',
      disconnected: 0,
      connected: 1,
      connecting: 2,
      disconnecting: 3,
      uninitialized: 99
    },
    _readyState: 1,
    _closeCalled: false,
    _hasOpened: true,
    _listening: false,
    _connectionOptions: {
      useNewUrlParser: true,
      useFindAndModify: false,
      useUnifiedTopology: true,
      useCreateIndex: true,
      promiseLibrary: [Function: Promise]
    },
    client: MongoClient {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      s: [Object],
      topology: [ReplSet],
      [Symbol(kCapture)]: false
    },
    name: null,
    '$initialConnection': Promise { [Circular] },
    db: Db {
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      s: [Object],
      serverConfig: [Getter],
      bufferMaxEntries: [Getter],
      databaseName: [Getter],
      [Symbol(kCapture)]: false
    }
  }
}

Advertisement

Answer

you can do like this for using transaction in mongoose:

Note:for using transaction you need to replica mongodb, so you should Convert a Standalone to a Replica Set, and need to add retryWrites: false as argument in mongoose.createConnection()

connect to mongoose :

      await mongoose.connect(`mongodb://localhost/namedb`, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
        retryWrites: false
      });
const mongoose = require("mongoose");

const sess = await mongoose.startSession();
sess.startTransaction(); 
await teacher.save({ session: sess }); // a query
student.messeges.push(); // do somthing
await student.save({ session: sess }); //// a query
await sess.commitTransaction();

for using replica set in localhost you should stop mongod service and run this code

mongod --port 27017 --dbpath C:datars1 --replSet m101 --bind_ip localhost

C:datars1 data stored path

 rs.initiate()
Advertisement