Introduction
In this Introduction of MongoDB in NodeJS, you will learn the basics of MongoDB and how to connect to a MongoDB database in NodeJS.
What is MongoDB
MongoDB is a document-oriented database solution. It uses JSON-like documents with schema. These terms will be explained later.It’s has several advantages. Some of them are:
- It’s performant, fast and extremely scalable.Furthermore, it has built in replication, and is flexible.
- Unlike mySQL or other relational databases you don’t need to map out your data structure beforehand, you don’t need to create all your tables, your columns and take the stress about deciding what data type your data is i.e VARCHAR or STRING.
- Other than that, the MongoDB API is extremely easy to learn and supports a plethora of languages including JavaScript, so you feel right at home whenever you develop apps involving MongoDB.
Basic Terminology
Before we get our feet wet, there are some keywords you should keep in mind.
- Documents : They are simple data records. It is the basic unit of storing data in a database. If you have a background in relational databases, you can think of documents as a ROW. Documents comprise of field-and-value pairs. A simple example of a document can be:
{
name: 'Rue',
Age : 20,
occupation:'Student'
}
- For every field , there will be a value . For example, here , one of the fields is name and its associated value is ‘Rue’
- Collections : A set of documents within a database. A database can have multiple collections. For relational database users, they are similar to tables.
- Queries : They are used to specify the conditions that determine which documents need to be selected for read,update, and delete operations.
The __id field
The __id field is mandatory for every MongoDB document. It is a primary key. In other words, it is used to uniquely determine a document in the database, thus it has a unique value. Even if you don’t specify this field, MongoDB will automatically generate an __id for you.
Installing MongoDB
To get started, first you need to navigate to the MongoDB Community download page. We are installing this software to view and create documents and collections without any code. If you are developing on Windows, it’s preferable to install an MSI installer. The download options should look like this:
In the end, the installation wizard will do the job for you.When it’s done, verify that the installation has been done correctly by going to your command line and typing mongod
When that’s done, it’s time to get our feet wet!
Getting started
Project creation
Before writing some code, let’s build our project like so:
mkdir myMongoDBApp #create project
cd myMongoDBApp
npm init -y #initialize project
npm install mongodb
To learn more about NPM, click here.
Database initialization
We now need to build our database. First, we need to require the mongodb module and then initialize an object of MongoClient:
const Mongo = require("mongodb");
const MongoClient = Mongo.MongoClient;
const client = new MongoClient("mongodb://localhost:27017", {
useUnifiedTopology: true,
});
In this code, we have initialized an object of Mongo.MongoClient which will give us access to the connect method, thus allowing us to create/connect to a database. The first parameter of the MongoClient constructor is the URL you want to connect to.To connect to database, we use the client.connect method. To do so, write the following:
client.connect((err) => {
if (err) console.log(err);
console.log("built database");
const db = client.db("myDB");
client.close();
});
In this code, we instructed Node to connect to a database named myDB
. In the end, we invoke the client.close
method to close the database and its connections.This will be the output:
Creating A MongoDB Collection
Now that our database has been built, we need to create a Collection to make a home for our Documents. To do so, we will utilize the db.createCollection() method
const createCollection = (db, callback) => {
db.createCollection("myCollection", (err, results) => {
if (err) console.log(err);
console.log("collection built");
callback();
});
};
In this code, we create a MongoDB collection named myCollection
through the help of a db instance .Then in the end, we executed a callback function. The presence of this callback is necessary as we will invoke client.close()
as a callback function.Now that the createCollection
method has been created, we will invoke this function within client.connect that we’ve already used above.In the end, all of your code should look like so:
const Mongo = require("mongodb");
const MongoClient = Mongo.MongoClient;
const client = new MongoClient("mongodb://localhost:27017/", {
useUnifiedTopology: true,
});
client.connect((err) => {
if (err) console.log(err);
console.log("connected to database");
const db = client.db("HussainsDatabase");
createCollection(db, () => {
client.close();
});
});
const createCollection = (db, callback) => {
db.createCollection("HussainsColletion", (err, results) => {
if (err) console.log(err);
console.log("collection built");
callback();
});
};
Conclusion
In this article, you finally learned the fundamentals of using MongoDB in Node.
A perhaps easier alternative to using the MongoDB Native API is using Mongoose API. In later tutorials, we will learn how to implement relational database functionality with Mongoose.This tutorial might seem confusing,but this topic is incredibly easy to wrap your head around if you apply the examples in your code. Remember, you’ll only learn when you start doing instead of just reading.Thank you so much for making it to then end of this tutorial! Have a great day!