DEV Community

Ahmad Ali
Ahmad Ali

Posted on

3 1

Connecting your App to MongoDB Atlas .. Important Notice

When you are using MongoClient to connect to MongoDB Atlas, it is important to know that there are 3 layers of connection.

1- connect to the cluster ..


mongo.connect(process.env.DATABASE_URL, (err, db) => {
  if(err) {
    console.log('Database error: ' + err);
  } else {
    console.log('Successful database connection');
  }
});


Enter fullscreen mode Exit fullscreen mode

using the code above will not deliver you to the database, although you will not get any errors, you will find that your operations on the database-collection are not successful.
again, there is no errors in this connection, so you won't understand why your interaction with the DB is not successful.

2- connect to the database:


//DB and authentication
mongo.connect(process.env.DATABASE, (err, cluster) => {
  if(err) {
    console.log('Database error: ' + err);
  } else {
    //connecting to the cluster
    console.log('Successful database connection');

    //connetcing to the database
    const db = cluster.db(DATABASE_NAME);
  }

 });

Enter fullscreen mode Exit fullscreen mode

in the code above, the

connection.db() or cluster.db()

function -if you want to think of it this way- to connect us our database.

3- connect to the collection :


//DB and authentication
mongo.connect(process.env.DATABASE_URL, (err, cluster) => {
  if(err) {
    console.log('Database error: ' + err);
  } else {
    //connecting to the cluster
    console.log('Successful database connection');

    //connetcing to the database
    const db = cluster.db(DATABASE_NAME);

   //conneting to the collection
   const coll = db.collection(COLLECTION_NAME);

   //do your stuff on the collection here.

  }
});


Enter fullscreen mode Exit fullscreen mode

in the code above we reached our collection, so we can do our operations on it correctly.

remember to put all of the code that is doing operations on Database inside the MongoClient connection.

Happy Coding..!!

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay