From cde930e0d63d23ccea80686d231ca83231b56003 Mon Sep 17 00:00:00 2001 From: Ruben Talstra Date: Sun, 15 Jun 2025 12:07:02 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20fix:=20Make=20MongoDB=20database?= =?UTF-8?q?=20name=20configurable=20via=20environment=20variable?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/db/connect.js | 5 ++++ api/lib/db/connect.js | 53 ------------------------------------------- 2 files changed, 5 insertions(+), 53 deletions(-) delete mode 100644 api/lib/db/connect.js diff --git a/api/db/connect.js b/api/db/connect.js index e88ffa51ed..706f67cc07 100644 --- a/api/db/connect.js +++ b/api/db/connect.js @@ -1,6 +1,7 @@ require('dotenv').config(); const mongoose = require('mongoose'); const MONGO_URI = process.env.MONGO_URI; +const MONGO_DB_NAME = process.env.MONGO_DB_NAME; if (!MONGO_URI) { throw new Error('Please define the MONGO_URI environment variable'); @@ -33,6 +34,10 @@ async function connectDb() { // useCreateIndex: true }; + if (MONGO_DB_NAME) { + opts.dbName = MONGO_DB_NAME; + } + mongoose.set('strictQuery', true); cached.promise = mongoose.connect(MONGO_URI, opts).then((mongoose) => { return mongoose; diff --git a/api/lib/db/connect.js b/api/lib/db/connect.js deleted file mode 100644 index 706f67cc07..0000000000 --- a/api/lib/db/connect.js +++ /dev/null @@ -1,53 +0,0 @@ -require('dotenv').config(); -const mongoose = require('mongoose'); -const MONGO_URI = process.env.MONGO_URI; -const MONGO_DB_NAME = process.env.MONGO_DB_NAME; - -if (!MONGO_URI) { - throw new Error('Please define the MONGO_URI environment variable'); -} - -/** - * Global is used here to maintain a cached connection across hot reloads - * in development. This prevents connections growing exponentially - * during API Route usage. - */ -let cached = global.mongoose; - -if (!cached) { - cached = global.mongoose = { conn: null, promise: null }; -} - -async function connectDb() { - if (cached.conn && cached.conn?._readyState === 1) { - return cached.conn; - } - - const disconnected = cached.conn && cached.conn?._readyState !== 1; - if (!cached.promise || disconnected) { - const opts = { - bufferCommands: false, - // useNewUrlParser: true, - // useUnifiedTopology: true, - // bufferMaxEntries: 0, - // useFindAndModify: true, - // useCreateIndex: true - }; - - if (MONGO_DB_NAME) { - opts.dbName = MONGO_DB_NAME; - } - - mongoose.set('strictQuery', true); - cached.promise = mongoose.connect(MONGO_URI, opts).then((mongoose) => { - return mongoose; - }); - } - cached.conn = await cached.promise; - - return cached.conn; -} - -module.exports = { - connectDb, -};