Node, Express, Swig, and MongoDB - Getting Started With CRUD

Let’s create a basic CRUD app using Node, Express, Swig, and MongoDB.

This tutorial utilizes Node v0.12.5, Express v4.13.1, Swig and Mongoose v4.1.3.

Getting started

The -g flag indicates that you want to install the package globally, on your entire system.

Navigate to a convenient directory, like your “Desktop” or “Documents”, then create the boilerplate:

Check out the project structure:

Don’t worry about the files and folders for now. Just know that we have created a boilerplate that can be used for a number of Node/Express applications. This took care of the heavy lifting, adding common files, folders, and scripts generally associated with all apps.

Notice the package.json file. This stores your project’s dependencies, which we still need to install:

Now let’s install Mongoose and Swig:

The --save flag adds the dependencies and their versions to the package.json file. Take a look.

Sanity check

Let’s test our setup by running the app:

Navigate to http://localhost:3000/ in your browser and you should see the “Welcome to Express” text. Once done, kill the server by pressing CTRL-C.

Nodemon

Before moving on, let’s setup Nodemon so that you can run your app and watch for code changes without having to manually restart the server. Check out the link above to learn more.

Let’s test again:

In your terminal you should see:

Essentially, Nodemon is watching for code changes, and if they do occur, then it will refresh the local server for you so you don’t have to constantly kill the server then start it back up. It saves a lot of time and keystrokes.

Awesome. With the setup done, let’s build something!

Routes

Grab your favorite text editor (such as Sublime or Atom), and then open the main file, app.js, which houses much of the business logic. Take a look at the routes:

Understanding how routes work as well as how to trace all the files associated with an individual route is an important skill to learn. You’ll be able to approach most applications and understand how they work just by starting with the routes.

Let’s look at this route:

Here, we know that this route is associated with the /users endpoint. What’s an endpoint? Simply navigate to http://localhost:3000/users.

The end user navigates to that endpoint and expects something to happen. That could mean some HTML is rendered or perhaps JSON is returned. That’s not important at this point. For now, let’s look at how Node handles the logic for “handling routes”.

Also, within that route, you can see the variable users. Where is in this file? It’s at the top, and it loads in another file within our app:

Open that file:

What’s happening here? Essentially when that endpoint is hit, it responds by sending text in the form of a response to the end user - “respond with a resource”. Now, of course you don’t always have to send text. You could respond with a template or view like a Jade or Swig template file that gets rendered into HTML. We’ll look at how this works in just a minute when we add our own routes.

Make sure you understand everything in this section before moving on.

Let’s now add a new route that renders a HTML form to the end user.

Start by adding the route handler in the app.js file:

Remember this simply means app.use('/ENDPOINT', VARIABLE_NAME);,

Use the api variable to require a JS file within our routes folder.

Take a look in the terminal. You should see an error, indicating Node can’t find the ./routes/api module. We need to create it!

Create a new file called api.js in the “routes” directory. Add the following code:

Do you remember what this code res.send('Just a test'); will do? If not, review the previous section.

Navigate to http://localhost:3000/api/superheros. You should see the text “Just a test” on the page.

Swig

Swig is a templating language, which compiles down to HTML, making it easy to separate logic from markup. For more on Swig, check out the Primer on Swig Templating.

Take a quick look at the layout.jade, index.jade, and error.jade files within the “views” folder. Right now these files are using Jade templating. Let’s update these files to remove Jade and add Swig. First, remove the .jade extension from each file and add a .html extension. Now we can update the actual syntax…

layout.html

index.html

error.html

Finally, update app.js by requiring the following dependency at the top of the file:

Then set Swig as the template engine by replacing app.set('view engine', 'jade'); with-

Jump back to the “views”, and take a look at layout.html and index.html. There’s a relationship between those two files. We define the base structure in the layout file, which contains common structure that can be reused in multiple places.

Do you see the block keyword?

What really happens when the index file is rendered is that it first renders the base template because of the extends keyword. So, the layout template then gets rendered, which eventually pulls in the child template, overwriting the block keyword with:

Hope that makes sense. If not, check out this resource for more info on template inheritance.

Setup api.html

Create a new file called api.html in the “views” directory, and then add the following code:

The same thing is happening here with inheritance. If you’re unfamiliar with Swig syntax, {{ title }} is essentially a variable, which we can pass in from ./routes/api.js.

Update ./routes/api.js by changing-

-to-

This just says, “When a user hits the /api/superheros endpoint, render the api.html file and pass in Superhero API as the title.”

Keep in mind that all Swig files are converted to HTML since browsers can’t read the Swig templating syntax.

Ready to test? Simple refresh http://localhost:3000/api/superheros.

Did it work? If yes, move on. If not, go back through this section and review.

Update api.html

So, let’s update the template to display a form:

Refresh your browser. Do you see the form? Try clicking save. What happens? Well, you just tried to send a POST request to the /api/superheros endpoint, which does not exist - so you should see a 404 error. Let’s set up the route handler.

POST requests (part 1)

Open api.js to add the logic for this new route:

Test this out again. Now, when you submit the form, we have the /api/superheros endpoint setup, which then grabs the text from the input box via req.body.name. Make sure the text is consoled in your terminal.

Okay. So, we are handling the routes and rendering the right template, but we still need to setup Mongoose to save the data from our form before we can finish with the POST request.

Mongoose

Mongoose is used for interacting with MongoDB. Start with defining the Schema, which then maps to a collection in Mongo.

Create a file called database.js in your app’s root directory, then add the following code:

Here, we required/included the Mongoose library along with a reference to the Schema() method. As said, you always start with defining the schema, then we linked it to collection called “superheros”. Finally, we opened a connection to an instance of our local MongoDB.

If you don’t have the MongoDB server running. Do so now. Open a new terminal window, and run the command sudo mongod. If you need to set up MongoDB, follow the Installation steps here.

Next, open app.js and require the Mongoose config at the very top of the file:

With Mongoose setup, we need to update api.js to create (via POST) and read (via GET) data from the Mongo collection.

GET requests (all resources)

Open api.js. Require Mongoose as well as the superheros model, which we already created:

Now, update the function handling GET requests:

Superhero.find() grabs all superheros from the Mongo collection, which we assign to the variable superheros. We can now use that variable in the Swig template.

Update api.html to display superheros

Let’s add a loop to iterate through the superheros and then display the name key from the collection.

Do you remember where we set the name key? Check out the database schema in database.js.

Before this will actually work - e.g., display superheros - we first need to add the logic to insert data into the Mongo collection.

POST requests (part 2)

Back in api.js, update the function for handling POST requests:

This simply saves a new superhero, which again is grabbed from the form via req.body.name.

Sanity Check

Refresh you app. Add some superheros. If you’ve done everything correctly, the superheros should be displayed beneath the form.

GET requests (single resource)

Update the list item in the HTML file like so to give each item a unique URL.

Now, let’s add a new route handler to api.js to display a single superhero:

What’s next? A new template. superhero.html:

Test this out.

PUT requests

Since most browsers do not handle PUT or DELETE requests, we need to use the method-override middleware to handle such requests.

Install via NPM:

Then define the middleware just below the view engine setup in app.js:

Finally, add the route handler to api.js:

Here, we are simply searching Mongo for the correct superhero via the Mongo ID and then updating the superhero name, which comes from the form, req.body.name. By setting new to true, we’re able to grab the updated superhero information after the changes are made in Mongo. Try removing this option. What happens?

DELETE requests

With the button already set up in the template, we just need to add the route handler to api.js:

Again, we’re querying the database by the Mongo ID and then removing it. Simple, right?

Conclusion

That’s it. Post your questions below. Grab the code from the repository. Cheers!