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');
}
});
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);
}
});
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.
}
});
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)