For a long time, I didn’t dare venture into back end development. I felt intimidated because of my lack of an academic background in programming.
I remember when I eventually built up the courage to try back end development. I had such a hard time understanding the documentation for Express, MongoDB, and Node.js that I gave up.
I eventually went back and worked through my confusion. Now, one year later, I understood how to work with these tools. So, I decided to write this comprehensive tutorial so you won’t have to go through the same headache that I went through.
CRUD, Express and MongoDB are big words for a person who has never touched any server-side programming in their life. Let’s quickly introduce what they are before we diving into the tutorial.
Express is a framework for building web applications on top of Node.js. It simplifies the server creation process that is already available in Node. In case you were wondering, Node allows you to use JavaScript as your server-side language.
MongoDB is a database. This is the place where you store information for your web websites (or applications).
CRUD is an acronym for Create, Read, Update and Delete. It is a set of operations we get servers to execute (POST, GET, PUT and DELETE respectively). This is what each operation does:
If we put CRUD, Express and MongoDB together into a single diagram, this is what it would look like:
Does CRUD, Express and MongoDB makes more sense to you now?
Great. Let’s move on.
We’re going to build an application simple list application that allows you to keep track of things within a list (like a Todo List for example).
Well, a todo list is kind of boring. How about we make a list of quotes from Star wars characters instead? Awesome, isn’t it? Feel free to take a quick look at the demo before continuing with the tutorial. Also, this is where you can find the finished code for the application.
By the way, what we’re building isn’t a sexy single page app. We’re mainly focusing on how to use CRUD, Express and Mongo DB in this tutorial, so, more server-side stuff. I’m not going to emphasize style.
You’ll need two things to get started with this tutorial:
To check if you have Node installed, open up your command line and run the following code:
$ node -v
You should get a version number if you have Node installed. If you don’t, you can install Node either by downloading the installer from Node’s website or downloading it through package managers like Homebrew (Mac) and Chocolatey (Windows).
Start by creating a folder for this project. Feel free to call it anything you want. Once you navigate into it, run the npm init command.
This command creates a package.json file which helps you manage dependencies that we install later in the tutorial.
$ npm init
Just hit enter through everything that appears. I’ll talk about the ones you need to know as we go along.
The simplest way to use node is to run the node command, and specify a path to a file. Let’s create a file called server.js to run node with.
$ touch server.js
When the execute the server.js file, we want to make sure it’s running properly. To do so, simply write a console.log statement in server.js:
console.log('May Node be with you')
Now, run node server.js in your command line and you should see the statement you logged:
Great. Let’s move on and learn how to use Express now.
We first have to install Express before we can use it in our application. Installing Express is pretty easy. All we have to do is run an install command with Node package manager (npm),which comes bundled with Node.
Run the npm install express — save command in your command line:
$ npm install express --save
Once you’re done, you should see that npm has saved Express as a dependency in package.json.
Next, we use express in server.js by requiring it.
const express = require('express');
const app = express();
The first thing we want to do is to create a server where browsers can connect to. We can do so with the help of a listen method provided by Express:
app.listen(3000, function() {
console.log('listening on 3000')
})
Now, run node server.js and navigate to localhost:3000 on your browser. You should see a message that says “cannot get /”.
That’s a good sign. It means we can now communicate to our express server through the browser. This is where we begin CRUD operations.
The READ operation is performed by browsers whenever you visit a webpage. Under the hood, browsers sends a GET request to the server to perform a READ operation. The reason we see the “cannot get /” error is because we have yet to send anything back to the browser from our server.
In Express, we handle a GET request with the get method:
app.get(path, callback)
The first argument, path, is the path of the GET request. It’s anything that comes after your domain name.
When we’re visiting localhost:3000, our browsers are actually looking for localhost:3000/. The path argument in this case is /.
The second argument is a callback function that tells the server what to do when the path is matched. It takes in two arguments, a request object and a response object:
app.get('/', function (request, response) {
// do something here
})
For now, let’s write “Hello World” back to the browser. We do so by using a send method that comes with the response object:
app.get('/', function(req, res) {
res.send('Hello World')
})
// Note: request and response are usually written as req and res respectively.
I’m going to start writing in ES6 code and show you how to convert to ES6 along the way as well. First off, I’m replacing the function() with the ES6 arrow function. The below code is the same as the above code:
app.get('/', (req, res) => {
res.send('hello world')
})
Now, restart your server by doing the following:
Then, navigate to localhost:3000 on your browser. You should be able to see a string that says “Hello World”.
Great. Let’s change our app so we serve an index.html page back to the browser instead. To do so, we use the sendFile method that’s provided by the res object.
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html')
// Note: __dirname is the path to your current working directory. Try logging it and see what you get!
// Mine was '/Users/zellwk/Projects/demo-repos/crud-express-mongo' for this app.
})
In the sendFile method above, we told Express to serve an index.html file that can be found in the root of your project folder. We don’t have that file yet. Let’s make it now.
touch index.html
Let’s put some text in our index.html file as well:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MY APP</title>
</head>
<body>
May Node and Express be with you.
</body>
</html>
Restart your server and refresh your browser. You should be able to see the results of your HTML file now.
This is how Express handles a GET request (READ operation) in a nutshell.
At this point, you probably have realized that you need to restart your server whenever you make a change to server.js. This is process is incredibly tedious, so let’s take a quick detour and streamline it by using a package called nodemon.
Nodemon restarts the server automatically whenever you save a file that the server uses. We can install Nodemon by using the following command:
$ npm install nodemon --save-dev
Note: The reason we’re using a — save-dev flag here is because we’re only using Nodemon when we’re developing. This flag would save Nodemon as a devDependency in your package.json file.
Moving on, Nodemon behaves exactly the same as node, which means we can run our server by calling nodemon server.js. However, we can’t do it in the command line right now because Nodemon isn’t installed with a -g flag.
There’s one other way to run Nodemon — we can execute Nodemon from the node_modules folder. The code looks like this:
$ ./node_modules/.bin/nodemon server.js
That’s a handful to type. One way to make it simpler is to create a script key in package.json.
{
// ...
"scripts": {
"dev": "nodemon server.js"
}
// ...
}
Now, you can run npm run dev to trigger nodemon server.js.
Back to the main topic. We’re going to cover the CREATE operation next.
The CREATE operation is performed only by the browser if a POST request is sent to the server. This POST request can triggered either with JavaScript or through a