MongoError: Cannot use a session that has ended

My Code: hatebin

My Error: “(node:28581) UnhandledPromiseRejectionWarning: MongoError: Cannot use a session that has ended”

This is for my discord bot, but on my pc everything works fine but on my server I get this error.
And I have the exact same mongoose version

Help pls

2 Likes

Hi @tomson welcome to the community.

If I have to guess, it’s due to the mongoose.connection.close(); statement in the function you posted.

Mongoose and the MongoDB node driver encourages the use of a global variable to connect once to the database during the lifetime of the application, and discourage the practice of connect-disconnect for every operation. This is because the MongoDB driver keeps a connection pool and will create/reuse connections as needed. Note that this is the reason why the connection object is a global object in Mongoose.

Could you try removing the mongoose.connection.close(); statement and see if the issue persists?

I would also replace the finally block there with catch to grab any errors in the try block.

Best regards,
Kevin

5 Likes

Thank you for the help brother :pray:

1 Like

@kevinadi Thanks lot