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' }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With