Search code examples
node.jsmongodbmongoosepm2koa

Nodejs with koa and Mongo - MongooseError: You can not `mongoose.connect()` multiple times while connected


I have an application in a aws machine in nodejs with koa and this application connects with a mongodb on a different aws machine. The error I am getting is MongooseError: You can notmongoose.connect()multiple times while connected. I am also running the application with pm2

this is the code to connect to the db:

    const mongoose = require('mongoose');
const { transform } = require('koa-bootstrap-service/lib/plugins');
const url = require('url');

const config = require('../../config/index');

mongoose.Promise = Promise;

function makeMongoUrl() {
    const dbSettings = config.mongoDb;
    if (!dbSettings) {
        return false;
    }

    if (dbSettings.url) {
        return dbSettings.url;
    }

    const urlObj = {
        hostname: dbSettings.host,
        port: dbSettings.port,
        pathname: `/${dbSettings.db}`,
        query: dbSettings.options,
        protocol: 'mongodb',
        slashes: true,
    };
    if (dbSettings.username) {
        urlObj.auth = `${dbSettings.username}:${dbSettings.password || ''}`;
    }
    return url.format(urlObj);
}

function connectMongoDb() {
    mongoose.plugin(transform.middleware());
    mongoose
        .connect(makeMongoUrl(), {
            useNewUrlParser: true,
            useCreateIndex: true,
            useFindAndModify: false,
            keepAlive: 1,
            connectTimeoutMS: 30000,
            reconnectTries: 30,
        })
        .then(() => {
            global.Logger.debug('Mongoose Connected');
        })
        .catch(({ stack }) => {
            global.Logger.error(stack);
            process.exit(0);
        });
}

connectMongoDb();

Solution

  • https://stackoverflow.com/a/56760259/11330560

    To quote:

    In mongoose version 5.6.1 the check was added https://github.com/Automattic/mongoose/pull/7905

    Revert to an older version for a quick fix.


    If in package.json the mongoose version is like this: ^5.x.y then caret ^ will make it update to the recent minor version, that is, up to the highest x (like 5.9.y but not 6.x.y).
    So one must force the older version.


    UPDATE: according to this answer: https://stackoverflow.com/a/56816168/11330560

    One must remove any other connections in any controller files, with only the main file being able to make connection.