Next.js Discord

Discord Forum

Next.js, next/link & mongodb

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
Disclaimer: It works, but only 75% of the times.
I'm having trouble with my database connection.
I made myself a little database.mjs to handle insertOne, etc. to reduce the clutter:
import { MongoClient } from 'mongodb';

let client;
let db;

export async function initDB() {
    if (!client) {
        try {
            client = new MongoClient(process.env.DB_HOSTNAME, {
                minPoolSize: 1,
                maxPoolSize: 50,
                maxConnecting: 10,
            });

            await client.connect();
            db = client.db(process.env.DB_NAME);
            console.log('Connected to database', db);
        } catch (err) {
            console.log('Error in initDB: ', err);
            throw err; // TODO: remove for production
        }
    }
    return { db, client };
}

export async function fetch(filter, fields, query) {
    try {
        const { db, client } = await initDB();
        if (!db) console.log('No db');
        const collection = db.collection(query);
        if (!collection) console.log('No collection');
        const response = await collection.findOne(filter, fields);

        return response;
    } catch (err) {
        throw err; // TODO: remove for production
    }
}

Upon navigating to a page that produces multiple fetch() calls 2~4 I am faced with this error:
No db <= my console.log in fetch()
Error in fetch @ database.js:  TypeError: Cannot read properties of undefined (reading 'collection')

Even though await initDB() is called, it somehow loses track of db only 1 line later.
I have also tried monitoring the connections via Compass -> Performance and notice the connections increase 2-6 upon each page load with no signs of connections disappearing.

4 Replies

Giant pandaOP
I, might've solved it. But I still have to monitor it.
I noticed db was occasionally undefined like the error said, but never bothered checking if client was undefined as well. In this case it wasn't so db was never 're-initialized' since client existed. Doing a simple
if(!db) {
  await client.connect(); //this line is optional
  db = client.db(process.env.DB_NAME);
}
has produced results.
I can't believe I spent an entire day (yesterday already) knowing db was undefined only to not realize I never redefine it.
Thrianta
I believe if components attempt to create multiple connections to mongo ( at least atlas ) then you will get errors about being unable to connect to the db.
@Thrianta I believe if components attempt to create multiple connections to mongo ( at least atlas ) then you will get errors about being unable to connect to the db.
Giant pandaOP
atlas as in mongodbs cloud version, right? I guess I should've mentioned I'm using a self-hosted/localhost one, mongodb-community via brew.
But interesting tidbit. I could've maybe also alleviated the issue by not just relying on if(!client) but rather if(!client || !client.isConnected())