Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get `Use of expired sessions is not permitted` error when using client session on mongodb nodejs application

My mongodb is 3.6 and my nodejs application is using mongo client 3.0. Below is the source code to use mongo client session to ensure causal relationship:

const session = client.startSession();
  const col = client.db('test').collection('test');
  col
    .insert({a: true}, {w: 0, j: false, session})
    .then(() => {
      return col.count({session});
    })
    .then(ret => {
      console.log(ret);
    }).catch(err => console.error(err));
  session.endSession();
}

I got below errors when running this application. It works without specifying the session for the insert or count command. I wonder how I can use session in this case.

    { MongoError: Use of expired sessions is not permitted
    at executeOperation (/Users/joey/dev/mongodb/demo/node_modules/mongodb/lib/utils.js:390:13)
    at Collection.count (/Users/joey/dev/mongodb/demo/node_modules/mongodb/lib/collection.js:1889:10)
    at col.insert.then (/Users/joey/dev/mongodb/demo/index.js:33:18)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
  name: 'MongoError',
  message: 'Use of expired sessions is not permitted' }
like image 946
Joey Yi Zhao Avatar asked Apr 13 '18 00:04

Joey Yi Zhao


1 Answers

I think I found out what wrong with my code. I need to move session.endSession(); to the then or catch since it is a promise call.

like image 135
Joey Yi Zhao Avatar answered Oct 13 '22 00:10

Joey Yi Zhao