Create an Express Application with Database

Express Application with Database MongoDB. We will learn how to create an express application.

In this post, we will learn how to create an express application with a database. Not only this, but also we will include a templating engine.

For the record, I don’t say you have to do the way I do here, but you will get the gist of what to do. So, let’s begin by creating a new folder.

Creating an Express Application

mkdir basic-express-app
cd basic-express-app

First of all, we should initialize the directory as an npm project. Let’s do that at first.

npm init -y

Now, if we see the package.json file, it will look like this.

{
  "name": "basic-express-app",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "keywords": [],
  "description": ""
}

Up to this point, there isn’t any useful information in this file, except for the main entry point. So, we create the entry point called index.js at first in the root directory.

With delay, let’s add express dependency in our project.

npm install --save express

Similarly, if you decide to use cookie in your project , you may need cookie-parser. In the same way, we will need morgan package to log what’s happening with the requests in the console. Furthermore, you need ejs package for the template engine which we will be using. Also note that, you are free too choose any of the templating engine from pug, jade, handlebars. Likewise, for displaying errors, we will be using http-errors package. To install all at once,

npm install --save cookie-parser ejs express http-errors morgan

Without further ado, let’s add some lines of code in index.js file.

const express = require('express'); // Our express app
const path = require('path');   // A built-in library for handling project path
const logger = require('morgan'); // For logging the requests output in console
const cookieParser = require('cookie-parser'); // For cookies
const createError = require('http-errors'); // For detailed error display in browser

Now, create an instance of express app as follows.

// Create instance of an app
const app = express();

Setting up View Engine

Next, we have to setup the templating engine in our express application. To do so, we have to create a directory views where our template files exist. Moreover, we have to tell express that, that folder is our views folder and our view engine is ejs.

// Setup template engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

An important point to note is that, express use middleware functions through which requests will. So we have to use the imported packages as middleware and use it using use keyword.

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

Furthermore, we have to indicate a public directory where our static files like scripts and stylesheets reside. So, This can be done as follows after creating the public folder in root directory.

app.use(express.static(path.join(__dirname, 'public')));

As mentioned earlier, we want to see 404 errors for the routes which we have not included in our project. It is important to realize that, we should carefully place the order in which the middleware execute. For now, let’s put it at the end of the file.

// catch 404 error and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, which only provides error in development
  // locals variable are automatically passed in the context in views
  
  res.locals.message = err.message;
  res.locals.error = err; // In development only, comment this out in production

  // Uncomment the following in production
  // res.locals.error = {};


  // render the error page
  res.status(err.status || 500);
  res.render('error'); // error.ejs in views folder
});

Of course, we will need an error.ejs file inside views folder since we have used it to render errors in the above code. Copy the following lines just to show the error.

<h1><%= message %></h1>
<h2><%= error.status %></h2>
<pre><%= error.stack %></pre>

Create Express Application Server

Now, we have to create a server which listen on a port (say, 8000).

app.listen(8000);
module.exports = app;

Until this point, if you run node index.js you will definitely see a 404 error stack because we have not defined any routes, however, we have created a server. An important thing to note that, if we make any change in our project, the project need to be rerun everytime. So, to make our job easier, we have a npm package nodemon. We have to add it as a development dependency.

npm install --save-dev nodemon

Similarly, we haven’t created any npm scripts. So, let’s update our scripts section in package.json file as follows.

"start": "nodemon index.js"

Now, we can easily run our development server using npm start command.

Creating Routes in Express Application

Further, we should now create a routes directory where we will organize our routes. Inside the routes directory, let’s create an index.js file which contains the routes for our / route.

So, inside routes directory, in index.js file, put a route like below.

const express = require('express');
const router = express.Router();

// GET home page
router.get('/', function (req, res, next) {
    res.json({ title: 'NepCodeX' });
});

module.exports = router;

We have to use this route in the app, hence we use this route as middleware in our app. Therefore, in index.js file of root directory, we use this middleware. We should note that, the use keyword support any number of arguments.

// Import routers
const indexRouter = require('./routes/index');

// Use it above the error handling middleware
app.use('/', indexRouter);

At this point, if we run the server, we will see the json we sent as response. Let’s use the view to render the our page. For that, create a file index.ejs inside views directory and place following lines of code.

<!DOCTYPE html>
<html>

<head>
    <title><%= title %></title>
</head>

<body>
    <h1><%= title %></h1>
    <p><%= message %></p>
    <p><%= date %></p>
</body>

</html>

And then we have to pass the message, date and title variable in the context. So, let’s modify the index.js route file.

// GET home page
router.get('/', function (req, res, next) {
    res.render('index', { title: 'NepCodeX', message: 'Congratulations! You have successfully created a route.', date: new Date() });
});

If your refresh the page in browser, you will definitely see something you intended. However, this is not enough. You have to create controllers and the controllers should handle the route requests. However, this is the basic of creating a server. You can surely add css and javascript inside the public directory. Now, it’s time to link our mongodb database. In this example, I have used the localhost, however, you can use online mlab database cluster.

Connecting to a MongoDB database for Express Application

Here, we will be using mongoose ODM to connect to mongodb server. Therefore, we have to add the dependency in our project.

npm i --save mongoose

Now, in index.js inside root directory, add the following code.

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/nepcodex', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log('Connected to NepcodeX database'))
    .catch((err) => console.log(err));

In this way, we can create an express application with a database support. If you liked this blog post and if it helped you to create an express application and link a database, be sure to check other posts too.

Do you want to know any interesting facts about javascript? You can check them here:

https://nepcodex.com/2019/09/some-interesting-facts-in-javascript/

https://nepcodex.com/2019/09/more-interesting-facts-in-javascript/

You can check the express documentation for the full api details through the following link. https://expressjs.com/en/4x/api.html

I am a Computer Engineer from Pulchowk Campus, IOE. I love programming, and music. Python, Java, Php, Javascript, Django, Laravel, Spring, express.js, etc. are my specialities.

1 Comment

Leave a Reply

%d bloggers like this: