In this MEAN Stack Tutorial, we are going to develop a RESTful API using Express.js and MongoDB. We will follow a step by step approach to make it easier for readers in developing their first RESTful API on MEAN stack.
Following are the steps to build the API:
- Step 1: Initialize the Project
- Step 2: Install Express
- Step 3: Install Express Generator
- Step 4: Create the Project
- Step 5: Install Dependencies
- Step 6: Install HBS, MONGO
- Step 7: Run Mongo
- Step 8: Create Mongo Service and Connect to Database
Step 1: Initialize the Project
- Create a folder with the project name such as todoapp.
- Open command prompt window on the project folder.
- Run the following command:
This command will create a package.json file with following details:1npm init
Step 2: Install Express
- Install express with following command:
1npm install express --save
Step 3: Install Express Generator
- Install express-generator using following command
1npm install express-generator --save
Step 4: Create the Project
- Use the following command to create the express project
1express todoapp
This will give the following output
1234567891011121314151617181920212223create : todoappcreate : todoapp/package.jsoncreate : todoapp/app.jscreate : todoapp/publiccreate : todoapp/routescreate : todoapp/routes/index.jscreate : todoapp/routes/users.jscreate : todoapp/viewscreate : todoapp/views/index.jadecreate : todoapp/views/layout.jadecreate : todoapp/views/error.jadecreate : todoapp/public/stylesheetscreate : todoapp/public/stylesheets/style.csscreate : todoapp/public/javascriptscreate : todoapp/public/imagescreate : todoapp/bincreate : todoapp/bin/wwwinstall dependencies:$ cd todoapp && npm installrun the app:$ DEBUG=todoapp ./bin/www
Step 5: Install Dependencies
- The package.json file will look like as following:
1234567891011121314151617{"name": "todoapp","version": "0.0.0","private": true,"scripts": {"start": "node ./bin/www"},"dependencies": {"body-parser": "~1.16.0","cookie-parser": "~1.4.3","debug": "~2.6.0","express": "~4.14.1","jade": "~1.11.0","morgan": "~1.7.0","serve-favicon": "~2.3.2"}}
- Install all the dependencies using following command:
1npm install
Note: You can find more helpful details on MEAN Stack especially AngularJS 1.x & AngularJS 2 here.
Step 6: Install HBS, MONGO
- Install mongo using following commands:
12345npm install --save mongonpm install --save mongodbnpm install --save monk
Step 7: Run Mongo
- Run mongod.exe it will start the MongoDB.

- Connect to todoapp databse using following command:

Step 8: Create Mongo Service and Connect to Database
- On app.js file add mongo database as following:
123var mongo = require('mongodb');var monk = require('monk');var db = monk('localhost:27017/todoapp'); - Create a middleware to connect to database
1234app.use(function(req,res,next){req.db = db;next();}); - Create a new router for todo in ‘routes/todo.js’ file
1234567891011121314151617var express = require('express');var router = express.Router();/* GET todos listing. */router.get('/', function(req, res) {res.send('Show todo list with delete and update feature (RUD)');});/* render NEW To-do form page. todos/new is a route path*/router.get('/new', function(req, res) {res.render('new_todo',{title:'Add new To-Do'});});module.exports = router; - In app.js add the router for initialization
12var todos = require('./routes/todos');app.use('/todos', todos); - Create a new form template inside views folder with the name ‘new_todo.jed’
12345678910111213141516extends layoutblock contenth1= titleform(name="new_todo", method="post", action="/todos/add_todo")div.inputspan.label Titleinput(type="text", name="title")div.inputspan.label Due Dateinput(type="text", name="dueDate")div.inputspan.label Descriptiontextarea(name="description", cols="40", rows="5")div.actionsinput(type="submit", value="add") - Run the app using the following command
1npm start - From browser if we run http://localhost:3000/todos/new, we can view the New todo page as following:

- Next step is the write the method that will be executed once the add-todo form is submitted in routes/todos.js file add the following router method.
1234567891011121314151617181920212223/* Add To-do to database*/router.post('/add-todo', function(req, res) {// Get the only one db instance in our appvar db = req.db;// Get POST values, It's easyvar title = req.body.title;var dueDate = req.body.dueDate;console.log('POST VALUES: ' + title + ' ' + dueDate);// Fetch from 'users' collectionvar todoCollection = db.get("todos");todoCollection.insert({'title' : title,'dueDate' : dueDate}, function(err, doc) {if(err) res.send('Problem occured when inserting in todo collection');else {console.log("Inserted");res.location('todos');res.redirect('/todos');}});}); - Now submitting the form will redirect to /todos/add-todo route and make a POST request. The todo will be saved in the database.
Hopefully, this MEAN Stack tutorial will serve as your first RESTful API using ExpressJS with MongoDB. We will come with more detailed technical tutorial on related technologies soon. Keep in touch 🙂





