Creating a Node + Express + MongoDB Web Application from Scratch

Welcome to this tutorial on how to build a CRUD web application using Node, Express and MongoDB. In order to follow along, you’ll need a code editor, passion and latest version of NodeJS installed on your local machine.

  1. If you’re on windows, open your Command Line (CMD) or Powershell. If you’re a Mac user, open your Terminal. Navigate to the directory where you want your project folder to be and do “mkdir myproject”. This will create a new directory. Navigate to your project directory and do “npm init -y”, which will create a package.json file with default configurations.
  2. Install Express, EJS, Body-parser and Mongoose by doing “npm install express ejs mongoose body-parser –save” or the shorthand version, “npm i express mongoose body-parser ejs -S”. Express is a NodeJS framework. EJS is a javascript templating engine. Body parser is used to parse form data. Mongoose is an ORM (Object relation Model) used to access to and manipulate MongoDB data.
  3.  Now open your favorite code editor (mine is Sublime Text <3). On the root level, create a server.js file. We start by importing the dependencies.
    const express = require('express');
    const bodyParser = require('body-parser');
    const mongoose = require('mongoose');
    const path = require('path');
    
    // instantiate the Express App
    const app = express();
    
    // if localhost -> 8080, else -> whatever in the env.
    const PORT = 8080 || process.env.PORT;
    
    // set the view engine to EJS
    // create a new folder called "views" annd put the .ejs files in it
    app.set('view engine', 'ejs');
    
    // making "public" directory for assets 
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.get('/', (req, res) => {
    	res.render('index');
    });	
    
    // run the application on PORT
    app.listen(PORT, () => console.log(`App running on port: ${PORT}`));
    Server.js
  4. In your root directory, create 2 new folders, “public”, to hold our assets, and “views” to put the EJS templates in.
  5. Navigate inside your “views” folder and make a new folder called “partials” that will hold partial views such as Footer, Navbar, Sidebar etc.
  6. Inside the “views” folder, make a new file and call it “index.ejs”. This file is going to be rendered whenever a GET request is made to http://localhost:8080/
    <!DOCTYPE html>
    <html>
    <head>
    	<title>Node + Express + Mongo Web Application</title>
    </head>
    <body>
    	<% var title = "web app" %>
    	<h1><%= "Welcome to my " + title + "!" %></h1>
    </body>
    </html>
    index.ejs

    You can learn more about EJS by reading their official documentation. Few alternatives to EJS are Handlebars, Jade, Mustache and Pug.

  7. Now we can pass data from our server.js to file to our views.

 

To be continued.. 🙂