Search code examples
amazon-web-servicesmongooseaws-documentdb

Mongoose DocumentDB connection fails through SSH tunnel


I am trying to connect to AWS DocumentDB with Node.js/Typescript and Mongoose. I have an EC2 instance setup as SSL tunnel, which works great. I can connect to DocumentDB locally with Studio3T and mongo-cli. This command works mongo --sslAllowInvalidHostnames --ssl --sslCAFile rds-combined-ca-bundle.pem --username <username> --password <password>

But if I try to connect to the same database with Mongoose, it fails. This is my code and the error:

const options = {
  dbName: "prodDB",
  user: connectionData.username,
  pass: connectionData.password,
  tls: true,
  tlsCAFile: "../rds-combined-ca-bundle.pem",
  tlsAllowInvalidHostNames: true,
};
try {
  await connect("mongodb://localhost:27017", options);
} catch (error) {
  console.log(error);
}

MongooseServerSelectionError: connect EHOSTUNREACH imagine-ip-address-here:27017
reason: TopologyDescription {
  type: 'ReplicaSetNoPrimary',
  servers: Map(1) {
    'censored:27017' => [ServerDescription]
  },
  stale: false,
  compatible: true,
  heartbeatFrequencyMS: 10000,
  localThresholdMS: 15,
  setName: 'rs0',
  commonWireVersion: 7,
  logicalSessionTimeoutMinutes: undefined
}

At this point, I have tried pretty much any possible config in Mongoose and I am getting desperate. Any help is appreciated


Solution

  • This seems to be an issue with mongoose versions >= 6. Downgrading Mongoose to version 5.13.8 works without a problem. Mongoose devs are apparently aware of this issue: https://github.com/Automattic/mongoose/issues/11105