Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Getting Error "Cannot use a session that has ended" when inserting into a collection

Hi!

Just getting started with MongoDB and having some newbie problems :grin:

I’m using the node.js Driver and trying a simple example of inserting some data into a new DB and Collection using the code directly from the driver docs:

const uri = `mongodb+srv://<username>:<password>@<cluster>t/test?retryWrites=true&w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect((err, client2) => {
  ifError(err)
  const db = client2.db("moving-db");
  const collection = db.collection("testing");
  console.log('Connected to the server', db.databaseName, collection.collectionName);
  const s = {
      name: 'Test Session',
      created: '2020-05-19',
      provider: 'TocBox'
  }
  collection.insertOne(s, function(err, r) {
      console.log('inside insertOne')
      ifError(err);
      console.log(r);
  });

  client2.close();
});

The console.log statements show that I am connected to the server OK, but the call to insertOne is returning the error “Cannot use a session that has ended”

Any ideas?

I should add that I am using MongoDB driver version 3.5.7 against an Atlas cluster.

I figured it out - simple problem.

Moved the statement client2.close() inside the callback of insertOne(…)

1 Like