Connecting MongoDB to Node.js

If you read my post Getting Started with MongoDB, I went over some basic instructions to start a mongoDB server on a windows PC. This post will be all about connecting that database to a local Node.js express back-end, so if you aren’t up to speed with Mongo be sure to check out that post and have your Mongo server up and running. Also, if you don’t have Node.js installed, go here and grab the latest version to get that installed.

Now that we have Node.js installed and our MongoDB server running we can get started. Open up a new terminal and cd to the parent directory you’d like to work in. Run mkdir project-folder to create a new folder for our project. I will call the folder todos-backend since this will be a back-end for a classic todo app once it’s finished. Next, you can cd into the project directory and install the dependencies. For this app’s back end we will just need three dependencies, express, mongoose, and body-parser. Express is the framework we will use to build out the back-end, mongoose is the sexiest Node.js MongoDB object modeling tool around, and body-parser is a popular tool to parse incoming request bodies. So we can run npm install express mongoose to get these installed. Once the installation is finished let’s create the index.js file, you can run cd .> index.js to create it from the terminal. Inside this file, we can add a few things to get our server spinning, go ahead and copy/paste the code below and save the file.

There isn’t much going on in this file yet, we are just requiring express and telling it to listen on port 8081. When the server starts we are printing a message to the console so we know it’s up. You can run node index.js to start the server and you should then see the startup message print to your terminal. Running the node command to start the server works but for development purposes we really want to install nodemon, which is a pretty cool package that will automatically restart our server every time we make changes to a file. Without nodemon, every time we make changes to a file we would have to manually restart the server for the changes to take effect. So let go ahead and shut down the server by hitting ctrl+c and then y in the terminal. Now we can run npm install -g nodemon to install nodemon globally to your system path. Instead of using the node command when starting the server we can now use nodemon instead.

With our server up and running we can finally start building our data models. But before we do that let’s add some structure to our project, you can run mkdir models routes handlers to create 3 new directories. The models folder will contain our mongoose data models, the routes folder will handle our server’s routes (the part of the url after the domain), and the handlers is where we will write the code to handle the incoming requests to our routes. This all may seem a little bit abstract at the moment but I promise it will make sense soon! So let’s recap, we should now have our project directory with those 3 folders and the index.js file. Lets cd into the models folder and start there.

Inside the models directory lets create two new files, another index.js and a todo.js. This index.js file will connect our express back-end to the local Mongo database we started earlier and the todo.js file will house our schema for a todo. The index.js file should look like

First, we are requiring mongoose and setting debug to true, which will print helpful messages to the console when we interact with the database. We also want to use ES6 promises with mongoose and set up some options that suit our development needs. We connect to the database with those options and note that whatever you put after localhost part of the connection url will be the name of your database. If you change the name and the server restarts it will connect to a fresh database with the new name. At the bottom, we require an export from our todo model, which we haven’t created yet so starting the server at this point will throw an error. So let’s add our schema for a todo to the todo.js file we created inside the models directory earlier. For this app we just need three properties for our todo schema which you can see below.

With mongoose, a schema is just an object in JavaScript, which is really nice! Our three properties are pretty simple, just a string for the todo title, a Boolean so we can complete a todo, and we will leverage the method to add a created date which will help with sorting on the front-end. Finally, at the bottom, we are just going to want to note the syntax to export this schema. In MongoDB our schema will map back to a collection and our properties will define how each document is structured in that collection. For this schema a document will be an individual todo and each document will be stored in the same Todo collection.

With Mongo our schemas/models are always going to be singular (i.e todo, user, comment, post, etc). We wouldn’t want to create a schema that holds an array of all the todos for several different reasons. Performance and scalability are the most obvious and there is also a 16MB storage limit on MongoDB documents to ensure that a single document cannot use too much RAM or bandwidth during transmission. When storing potentially long or nested arrays and objects just keep in mind the storage limit. To read more about schemas with mongoose you can read the docs here.

Now let’s cd back to the root of our project and run nodemon index.js to start the express app. We should see the message from our express app appear in the console just like before. You should also see some text output with information about the Todo schema we just created since we set debug to true. Check the other terminal that is running the local MongoDB and you should see a message showing 1 connection to the database. Now that we are connected, in my next post, I will go over how we can turn our express app into a simple RESTful JSON API that we will use to add, remove, or update information in the Mongo database.

Leave a Reply