'Problems implementing reconnection strategy for mongodb using mongoose on a replica set

I have an experimental app that uses a NodeJS backend which connects to a mongodb instance using mongoose. Mongodb is configured to run as single-node replica set to give me access to change streams which I use for real-time updates over a websocket connection.

For several reasons I'd like to be able to start the backend without the DB service running and have it connect as soon as it becomes available (primary reason: Docker startup). Also, I would like it to reconnect if the db server becomes unavailable for some reason.

A promising fix for reconnecting to mongodb seems to be https://stackoverflow.com/a/41859984/8447743. However, it does not seem to work in my case. It does work for delayed connection (mongod service starting after app), but gives an error on reconnection:

C:\Users\<Path to app>\node_modules\mongoose\node_modules\mongodb\src\cmap\connection.ts:740
          callback(new MongoServerError(document));
                   ^
MongoServerError: Cannot run getMore on cursor 8780071429437342673, which was created in session 993f2cbd-db02-4565-af56-f0c9a88ba012 - 47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=, without an lsid
    at MessageStream.messageHandler (C:\Users\<Path to app>\node_modules\mongoose\node_modules\mongodb\src\cmap\connection.ts:740:20)
    at MessageStream.emit (node:events:526:28)
    at MessageStream.emit (node:domain:475:12)
    at processIncomingData (C:\Users\<Path to app>\node_modules\mongoose\node_modules\mongodb\src\cmap\message_stream.ts:167:12)
    at MessageStream._write (C:\Users\<Path to app>\node_modules\mongoose\node_modules\mongodb\src\cmap\message_stream.ts:64:5)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at MessageStream.Writable.write (node:internal/streams/writable:334:10)
    at Socket.ondata (node:internal/streams/readable:754:22)
    at Socket.emit (node:events:526:28) {
  ok: 0,
  code: 50737,
  codeName: 'Location50737',
  '$clusterTime': {
    clusterTime: Timestamp { low: 2, high: 1650366308, unsigned: true },
    signature: { hash: [Binary], keyId: 0 }
  },
  operationTime: Timestamp { low: 2, high: 1650366308, unsigned: true }
}
[nodemon] app crashed - waiting for file changes before starting...

According to https://www.mongodb.com/docs/manual/reference/command/lockInfo/ I might able to get this lsid that seems to be missing, but I haven't found a way to make that known to mongoose for reconnecting. Is that possible somehow? Is there another way to avoid the error?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source