Connecting to MongoDB with NodeJS

In this article we will learn how we can use and connect to MongoDb with Node.js.

This tutorial is specifically designed for beginners, so if you have a bit of Node.js knowledge and you are just getting started with MongoDB, you are at the right place. This is the MongoDB NodeJS Tutorial for beginners.

MongoDB is a document oriented no sql database. MongoDB stores data in JSON like documents. This gives us the flexibility to have flexible fields in documents and change the data-structure with each document.

We will be using an npm package called as Mongoose which is by far the most popular orm/driver to connect to MongoDB.

In the following sections, I’ll cover the following points.

Connecting to MongoDB.

Creating and using a schema in Mongoose.

Querying MongoDB with Mongoose.

Setting up our environment

Before we start with the actual application, we need to make sure we have a few things installed and running on our machine.

Install MongoDB. Make sure you follow the installation steps provided on the website clearly, the installation differs depending on your OS.

Install Node.js. At the time of writing this article 10.15.0 is the latest LTS version.

Once both of these are installed, we need to start our MongoDB. On windows you can run by running mongod. In Linux mongod is added to the services so you can just do sudo service mongod start.

Mongoose connect function takes the uri and set of options (optional). The URI is comprised of mongodb server and the database name, eg : mongodb://{mongoserver}/{dbname}.

If you are coming from a mysql background, you might be wondering we didn’t even create a database named ciphertrick? In mongodb you don’t need to create a db before connecting to it, MongoDB does that for us internally, if the database name provided does not exits, MongoDb will create it for us.

In the above file we have added event listeners on various connection events, this is a healthy practice to do, so in case if something goes wrong debugging is easy.

At the end we are closing all db connections when our application terminates.

Now create a file named app.js, this will be the starting point of our app.

app.js

require('./db');

At this point, we are simply requiring our db file.

Let’s run our app and see what we get.

node app.js

If you have followed the tutorial correctly you should get the following output.

Mongoose default connection open to mongodb://localhost:27017/ciphertrick

As you can see above, we have defined a model person using mongoose. Defining Mongoose models provides some structure to otherwise unstructured collections. Now one might say MongoDB is made for unstructured data. Well, that is correct and you can also achieve that in here by just passing ‘strict:false‘ in options. But it is always a plus to have a rough idea how our MongoDB documents look, this makes it easier to interact with them and also helps others understand our code better.

Mongoose also provides inbuilt validations which is a very handy feature.

We have also defined two static methods, one for adding a new person and one for listing persons.

Static functions are directly defined on models and can be invoked by simply requiring the model. It is a good way to organize your functions with the model itself.

If you have read the code above, you will realize how easy it is to interact with MongoDB. It’s just like writing JavaScript. Also if you want to find a specific person by id you can just do…

this.find({_id: "5c4fb96536f7132ad4ccddfe"});

Okay, now that we have understood what we have done and have the code. Let’s just try to call it in our app.js file.

In the output you might also, see there are two fields createdAt and updatedAt which we had not defined in the model, that’s because we have timestamps:true set under options. Mongoose adds these fields for us.