3

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"
}

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

Comments

0

the reason this is happening is because you are trying to perform an action on the DB after you closed the connection, specifically the line:

JSON.parse(JSON.stringify(post))

You need to move this before your

await client.close()

and everything will be fine. The reason is that this is an mongoose object and not a plain javascript object, which you could receive alternatively by using .lean

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()
    .lean()

I was having a related issue with a test runner and mongodb connections which I managed to finally solve by using:

afterEach(async () => {
    // allow time for everything to complete
    await new Promise(r => setTimeout(r, 500));

    await mongoose.disconnect();
    await mongoose.connect(dbUri, { maxPoolSize: 2000 });
});

Maybe this can help someone one day loool

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.