openKB icon indicating copy to clipboard operation
openKB copied to clipboard

Cannot start openKB unless downgrading mongodb client library to 2.x

Open HuskyMoonMoon opened this issue 5 years ago • 2 comments

Since a breaking change of MongoDB client library from v2.x to v3.x, method MongoClient.connect() returns a Connection object instead of a Database object, caused app unable to start openKB using MongoDB as its database.

HuskyMoonMoon avatar Mar 26 '20 10:03 HuskyMoonMoon

Assuming your mongodb connection string is something like this:

mongodb://foo-bar-baz:xxxxxxxyxxxxyxyxyxyxy@some-production-cluster-0-shard-XX-XXXXXX.foo.bar.net:27018/foo-bar-staging?ssl=true&replicaSet=foo-bar-cluster-0-shard-0&authSource=admin&retryWrites=true

You can add a few lines to the app.js file to extract the mongodb database name from the connection string. The mongodb 3.x driver is different, it passes back a client instead of a db, so you need to create a db instance. ie: let db = client.db(dbName);

I've tested out the code below and it works. Not sure if this will work for all connection strings though, and it's a bit of a hack... ie: maybe we should be passing in the db name instead. It also doesn't handle errors, like if the regex group 1 doesn't exist. But feel free to use it if you want.

    MongoClient.connect(config.settings.database.connection_string, {}, (err, client) => {
        // On connection error we display then exit
        if(err){
            console.error('Error connecting to MongoDB: ' + err);
            process.exit();
        }

        const mongoDBNameRegEx = "^(?:mongodb:\\/\\/)(?:.+)(?:\\/+)(.+)(?:\\?+)(?:.+)";
        let dbName = config.settings.database.connection_string.match(mongoDBNameRegEx)[1];
        let db = client.db(dbName);

philhack avatar Mar 29 '20 21:03 philhack

In november, Heroku will close its MongoDb addon, so I migrated my openKb database from heroku.com to mongodb.com. After this, the 'npm start' command always failed with "db.connection" error...

Thanks to this fix, it is now working again !

Sphinkie avatar Sep 19 '20 09:09 Sphinkie