Next.js Discord

Discord Forum

Mongoose with multiple connections

Unanswered
Azawakh posted this in #help-forum
Open in Discord
AzawakhOP
Hye, Im currently trying to get multiple dbs connected on my njs site with mongoose. I follwed the docs and got them connecting. But it seems when im doing nay form of query to the db, it always fails and returns a '.find() is not a function' error. Seems the issue is only affecting some collections and not all for some reason.

I have assigned my models to the correct connection as shown in the docs, yet the issue persists. I was looking to see if someone had any links to some blogs or guides on this sort of topic, the only ones ive seen online seem deserted and appear that the issue was never resolved for the OP. Any help or ideas are appriciated, for ref, here is my connection file:

const mongoose = require('mongoose');

let mainDbConnectionState = { connection: null, connecting: false };
let staffDbConnectionState = { connection: null, connecting: false };

// Function to create a new connection to mongo, to open up a new connection to a different database.
function makeNewConnection(uri) {
    const db = mongoose.createConnection(uri, {});

    db.on('error', function (error) {
        console.log(`MongoDB :: connection ${this.name} ${JSON.stringify(error)}`);
        db.close().catch(() => console.log(`MongoDB :: failed to close connection ${this.name}`));
    });

    db.on('connected', function () {
        // Enable debug mode while attempting to multi-connect dbs. REMINDER: REMOVE IN PROD
        mongoose.set('debug', function (col, method, query, doc) {
            console.log(`MongoDB :: ${this.conn.name} ${col}.${method}(${JSON.stringify(query)},${JSON.stringify(doc)})`);
        });
        console.log(`MongoDB :: connected ${this.name}`);
    });

    db.on('disconnected', function () {
        console.log(`MongoDB :: disconnected ${this.name}`);
    });

    return db;
}

async function connectMongoDB() {
    if (!mainDbConnectionState.connecting) {
        mainDbConnectionState.connecting = true;
        mainDbConnectionState.connection = makeNewConnection(process.env.MONGODB_URI);
        await new Promise((resolve) => mainDbConnectionState.connection.once('connected', resolve));
        mainDbConnectionState.connecting = false;
    }

    if (!staffDbConnectionState.connecting) {
        staffDbConnectionState.connecting = true;
        staffDbConnectionState.connection = makeNewConnection(process.env.MONGODB_URI_STAFF);
        await new Promise((resolve) => staffDbConnectionState.connection.once('connected', resolve));
        staffDbConnectionState.connecting = false;
    }

    return {
        mainDbConnection: mainDbConnectionState.connection,
        staffDbConnection: staffDbConnectionState.connection,
    };
}

// Fetch the main database connection
async function getMainDbConnection() {
    if (!mainDbConnectionState.connection && !mainDbConnectionState.connecting) {
        await connectMongoDB();
    }
    return mainDbConnectionState.connection;
}

// Fetch the staff database connection
async function getStaffDbConnection() {
    if (!staffDbConnectionState.connection && !staffDbConnectionState.connecting) {
        await connectMongoDB();
    }
    return staffDbConnectionState.connection;
}

module.exports = { connectMongoDB, getMainDbConnection, getStaffDbConnection };


I do want to sress, that it does infact appear to connect to the db, and the debug logs do show some of the queries working as epected, using the correct db instance. But yeah, as stated, it appear some of the queries just don't work at all, while they did work beforehand. I have double checked my imports and done all basic ts steps.

2 Replies

Spotted Redshank
Hey, I'm also having this issue would anyone know how to fix this??
Spotted Redshank
Does anyone know?