Mongodb connection only once in next js

Viewed 54

I just started with Next js. The question I have is that in express projects we have a connection to the database once and we put it in the main file of the program, i.e. app.js. but in Next js as I understand so far, the connection to the database must be inside the api file. Doesn't this cause the connection to be reconnected every time the api is called? Is it necessary to have a file like app.js in order to connect to mongo inside it? thanks

1 Answers

create one separate file and add following code in that file.

import mongoose from 'mongoose';

const connection = {}

const dbConnect = async () => {
    if (connection.isConnected) return

    const db = await mongoose.
        connect(process.env.DB_URL, { useNewUrlParser: true, useUnifiedTopology: true })

    connection.isConnected = db.connections[0].readyState
}
export default dbConnect

now only you need to call dbConnect() function every where you are performing the db operation.

Related