Why nodejs server connects to Mongodb without connect command

Hi
I have the following code to add user to mongodb data base
in my server.js file i have following code

app.post("/AddUser",async (req,res)=>{

    const credintials= await req.body
    console.log(credintials)
    const result=await AddUser(credintials)
    
    

and AddUser function has the following code

import { MongoClient } from "mongodb";

const uri =
  "mongodb+srv://******@cluster0.xerwiw2.mongodb.net/?maxIdleTimeMS=5000";

const client = new MongoClient(uri);
async function AddUser(Credintials) {
  try {
    
    const res = await client
      .db("Projectman")
      .collection("Projectma")
      .insertOne({ email: Credintials.email, pass: Credintials.Password })
      .then((res) => {
        return res;
      })
      .catch((err) => {
        
        console.log(err);
        
      });
    
    if (res.acknowledged === true) {
      const user = await client
        .db("Projectman")
        .collection("Projectma")
        .findOne({ email: Credintials.email })
        .then((res) => {
          return res;
        })
        .catch((err) => {
          return "no user found";
        });

      return user;
    } else {
      return "error";
    }
  } finally {
    
    
    console.log("done");
  }
}


export default AddUser;

I have noticed that the nodejs server is always connected to mongodb database even if no
client.connect() function is used
is this correct

It happens because the NodeJs mongo driver execute a connect function when is executing an operation.

In your case, the pool connection is opened when you call .insertOne method.

On internal methods the driver call a executeOperationAsync that this one perform a call to connect a db.

And when the connection will be closed or it will remain open forever
and please advice is this the good practice or there is another better practice I can follow

It will be opened without time to close. Creating a connection is an operation that cost memory and CPU and Mongo prefers to keep them alive. The driver will use these connections in other operations, in case that need more connections will create them until maxPoolSize length.
It’s important to keep in mind that the driver has responsible to handle these connections and choose the connection to made an operation. You just need to configure the maxPoolSize that defines the maximum of connections opened at the same time. The default maxPoolSize is 100 connections, So mongo can keep 100 connections opened at the same time. In avg you will need 1Mb RAM for each connection opened. You must use these options with carefully.

The good practice can be use as the docs recommend.