mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Allow connection URL to be an async function

Open NPellet opened this issue 3 years ago • 2 comments

Prerequisites

  • [X] I have written a descriptive issue title
  • [X] I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Add the ability to pass a function to mongoose.connect:

    static connect(url: () => Promise<string>): Promise<MongoClient>;

This function would be called in the event of a reconnect, i.e. its result will not be cached.

Motivation

We want to introduce credential rotation on our MongoDB cluster. However, as far as I understand, during a reconnect, mongoose will attempt to re-use the same URL with the same credentials. If the credentials have rotated, the re-connection will fail.

Example

An example in our application:

  mongoose
    .connect(`${process.env.MONGODB_URL}/${process.env.DB_NAME}`)
// ...

What we'd like to use:

mongoose.connect( async function() {
  const creds = await fetchMongoDBCredentials();
  return `url_with_${creds}:port/${process.env.DB_NAME}`
});

NPellet avatar Oct 26 '22 14:10 NPellet

Why not wrap the two within an async function? Something like the following should be suitable:

export async function connect() {
  const creds = await fetchMongoDBCredentials();
  await mongoose.connect(`url_with_${creds}:port/${process.env.DB_NAME}`);
}

Mongoose will reuse the connection string if it has not changed, if the credentials have changed then a new connection will be created and any existing connection terminated.

karlbateman avatar Aug 13 '24 18:08 karlbateman

I believe the point of this issue was that the connection string can change

vkarpov15 avatar Aug 22 '24 01:08 vkarpov15