From 7b0f82c631ff5549cdc9a8e0ffcc705d067c2157 Mon Sep 17 00:00:00 2001 From: Samson Ssali Date: Fri, 5 Jan 2024 15:54:02 -0700 Subject: [PATCH] fix(generators): Harden mongodb.js to reliably extract database from any connection string (#3264) --- .../generators/src/connection/templates/mongodb.tpl.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/generators/src/connection/templates/mongodb.tpl.ts b/packages/generators/src/connection/templates/mongodb.tpl.ts index 64c3c38d7f..52815df3f7 100644 --- a/packages/generators/src/connection/templates/mongodb.tpl.ts +++ b/packages/generators/src/connection/templates/mongodb.tpl.ts @@ -17,10 +17,14 @@ declare module './declarations' { export const ${database} = (app: Application) => { const connection = app.get('${database}') as string - const database = new URL(connection).pathname.substring(1) - const mongoClient = MongoClient.connect(connection) - .then(client => client.db(database)) + + const databaseRegex = /\/([a-zA-Z0-9_\\-]+)(?:\?|$)/; + const databaseName = databaseRegex.exec(connection)?.[1]; + + const mongoClient = MongoClient.connect(connection) + .then(client => client.db(databaseName)); + app.set('${database}Client', mongoClient) } `