mrvautin / openKB

Open Source Nodejs Markdown based knowledge base (FAQ) app
https://openkb.markmoffat.com
MIT License
653 stars 200 forks source link

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

Open HuskyMoonMoon opened 4 years ago

HuskyMoonMoon commented 4 years ago

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.

philhack commented 4 years ago

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 theregex 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);
Sphinkie commented 4 years ago

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 !