reactjstypescriptmongodbnext.jsgetserversideprops

MongoDB NextJS connection error "attempted to check out a connection from closed connection pool"


I'm trying to make a connection to my MongoDB database in order to retrieve sone data.

When I'm setting up the connection without fetching anything, no issues. But when I'm trying to grab some data, the console throws me this:

attempted to check out a connection from closed connection pool

Note that the connection still returns true (see code below)

What it does

A console error. The client logs a {} (log is inside a useEffect hook)

what it should do

Return data fetched from database

mongodb init

const { MongoClient } = require('mongodb');

export function getClient() {

    let client
    let clientPromise

        // Local setup
        if (!process.env.MONGODB_URI) throw new Error("Invalid/missing database key")

        const uri = process.env.MONGODB_URI
        const options = {}

        client = new MongoClient(uri, options)
        clientPromise = client.connect()
        console.log("connected to development database")

    return clientPromise
}

getServerSideProps

export async function getServerSideProps(context: any) {
    try {
        const client = await getClient()

        const db = await client.db("db-name")

        const post = db
            .collection("articles")
            .find({"type": "nouvelle"},
                {projection: { "_id": 0, "title": 1, "titleSlug": 1, "type": 1, "imageUrl": 1, "author": 1 }})
            .sort({ $natural: -1 })
            .limit(2)
            .toArray()

        await client.close()

        return {
            props: { isConnected: true, post: JSON.parse(JSON.stringify(post)) },
        }
    } catch (e) {
        console.error(e)
        return {
            props: { isConnected: false, post: null },
        }
    }
}

Dependencies

{
    "@types/node": "18.15.9",
    "@types/react": "18.0.29",
    "@types/react-dom": "18.0.11",
    "eslint": "8.36.0",
    "eslint-config-next": "13.2.4",
    "mongodb": "^5.1.0",
    "next": "13.2.4",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "typescript": "5.0.2"
}

Solution

  • I found the stuff.

    The double async made the whole thing crash.

    So if you have this issue, instead of separating pointers like I did, prefer doing:

            const client = await getClient()
    
            const post = await client.db("db-name")
                .collection("articles")
                .find({"type": "nouvelle"},
                    {projection: { "_id": 0, "title": 1, "titleSlug": 1, "type": 1, "imageUrl": 1, "author": 1 }})
                .sort({ $natural: -1 })
                .limit(2)
                .toArray()