Todo Web App Using a MEAN Fullstack

Introduction

 
Before we start to code let us first understand a few things.
 

What is MEAN?

 
So, basically MEAN stands for MongoDB, Express, AngularJS, and NodeJS.
 
Now the question is, what are these?
 
  
Now we will use these amazing full-stack Javascript frameworks to build a Todo Web Application.
 
Let us now see which version we will be using for this tutorial.
 
Instruction
  • Clone the project: https://github.com/amitsin6h/todo-mean-app/
  • Cloud9 with blank Ubuntu project 
Step 1
 
Let’s start first by installing Nodejs.
 
To build our project we need to install Nodejs. Let’s see how to do that below.
 
Type the below command in the terminal to install nodejs.
  • $ sudo –s
  • $ curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
  • $ sudo apt-get install nodejs
  • $ exit
Once the installation process is done we can check our nodejs version using the below command.
 

$ node –v (display the node version)

 
We can also check our npm  (Node Package Manager) version using the below command.
 

$ npm –v (display the npm version)

 
Node Package Manager is basically used to build projects and to download nodejs library. 
 
Once done, we can now move to Step 2.
 
Step 2
 
Installing  MongoDB.
 
To install MongoDB we need to run the below command.
  1. $ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv   2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5
  2. $ echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list
  3. $ sudo apt-get update
  4. $ sudo apt-get install -y mongodb-org
Once we install our MongoDB, now we are ready for Step 3.
 
Step 3
 
Building our project. To build using the below command
  • First, create a separate directory for your project, in our case, it is [todo]
  • Run $ npm init command it will ask few things related to project like version and will create pacakage.json for the project.
Step 4
 
Installing Express. We can install express using the below command.
 

$ npm install express –save

 
and this will install the express and also add the package in the pacakage.json folder.
 
Our Complete Project Structure
 
Step 5
 
Starting our Nodejs Server.
 
Lets first create server.js file inside todo folder
 
todo/server.js
  1. //calling express library    
  2. var express = require('express');    
  3. var app = express();    
  4.     
  5. //GET request     
  6. app.get('/'function(req, res){    
  7.     res.send('<h1>Welcome to Todo Web Application!!');    
  8. });    
  9.     
  10. app.listen('8080'function(){    
  11.     console.log('Server Running!!');    
  12. });   
Now let’s start our server using the below command.
 
$ nodes server.js
 
Wooo!! Server Running :)
 
Now to access our application we need to follow the guide shown in the below image.
 
Now we will build our application frontend using Angularjs.
 
Step 6 - Creating Our Frontend
 
Before we build our front end let's create a folder named [app] inside the todo folder where we will store our frontend files and then we will see how to connect our fronted with the server.
 
Now  let’s start building our frontend using Angularjs.
 
todo/app/index.html
  1. <!doctype html>    
  2. <html lang="en" ng-app="todoApp">    
  3.   <head>    
  4.     <!-- Required meta tags -->    
  5.     <meta charset="utf-8">    
  6.     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">    
  7.     
  8.     <!-- Bootstrap CSS -->    
  9.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">    
  10.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>    
  11.     <script type="text/javascript" src="app/app.js"></script>    
  12.         
  13.     <title>Todo App | MEANjs</title>    
  14.     <style type="text/css">    
  15.         .bg-hackclub{    
  16.             background: #F34C5E;    
  17.             color: #fff;    
  18.         }    
  19.     </style>    
  20.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css" />    
  21.   </head>    
  22.   <body>    
  23.     <div class="jumbotron jumbotron-fluid bg-hackclub">    
  24.       <div class="container">    
  25.         <h1 class="display-4">Todo App</h1>    
  26.         <p class="lead">This is MEANjs built in web application for Hack Club.</p>    
  27.       </div>    
  28.     </div>    
  29.         
  30.     <div class="container">    
  31.         <div class="row" ng-controller="createTodoController">    
  32.           <div class="col-md-6 offset-md-2">    
  33.             <div class="input-group input-group-lg">    
  34.               <input  type="text" ng-model="todo.task" class="form-control" placeholder="Write your daily task here....." aria-label="Large" aria-describedby="inputGroup-sizing-sm">    
  35.             </div>    
  36.           </div>    
  37.               
  38.           <div class="col-sm-3">    
  39.             <button type="button" ng-click="createTodo()" class="btn btn-outline-info btn-lg" >Add Task</button>    
  40.           </div>    
  41.         </div>    
  42.         <hr>    
  43.         <div ng-controller="myCtrl">    
  44.                
  45.             <div class="row" ng-repeat="task in tasks.data">    
  46.               <div class="col-md-7 offset-md-2">    
  47.                 <div class="input-group mb-3">    
  48.                   <div class="input-group-prepend">    
  49.                     <div class="input-group-text">    
  50.                       <input type="checkbox" aria-label="Checkbox for following text input">    
  51.                     </div>    
  52.                   </div>    
  53.                    <h1 class="form-control">{{task.task}}</h1>    
  54.                         
  55.                   <div class="input-group-append">    
  56.                     <div class="input-group-text bg-danger" ng-click="deleteTask(task._id)">    
  57.                       <i class="fa fa-trash-o text-white"></i>    
  58.                     </div>    
  59.                   </div>    
  60.                 </div>    
  61.               </div>    
  62.             </div>        
  63.           </div>    
  64.       </div>    
  65.     </div>    
  66.   </div>    
  67.     
  68.     <!-- Optional JavaScript -->    
  69.     <!-- jQuery first, then Popper.js, then Bootstrap JS -->    
  70.     <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>    
  71.     <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>    
  72.     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>    
  73.   </body>    
  74. </html>   
Create an app.js file to load our angularjs components.
 
todo/app/app.js
  1. var app = angular.module('todoApp', []);    
  2. app.controller('createTodoController'function($scope,$http) {    
  3.    $scope.createTodo = function(){    
  4.        //console.log($scope.todo);    
  5.        $http.post('api/create/todo', $scope.todo)    
  6.         .then(function(success){    
  7.             //success callback    
  8.             console.log($scope.todo);    
  9.             console.log(success.status);    
  10.         }, function(error){    
  11.             //error callback    
  12.             console.log(error.status);    
  13.                 
  14.         });    
  15.    }    
  16.        
  17. });    
  18. app.controller("myCtrl"function($scope, $http) {    
  19.         
  20.     $http.get("api/get/tasks")    
  21.         .then(function (tasks) {    
  22.             $scope.tasks = tasks;    
  23.             //console.log(tasks);    
  24.         });       
  25.         
  26.     $scope.deleteTask = deleteTask;    
  27.         
  28.     function deleteTask(taskId) {    
  29.         $http.delete("/api/delete/task/"+taskId)    
  30.             .then(function(){    
  31.                 //success callback    
  32.                 console.log('success');    
  33.                     
  34.             },function(error){    
  35.                 //error callback    
  36.                 console.log('Error');    
  37.         });    
  38.     }               
  39. });   
Step 7
 
Let’s create our Database.
 
For creating a database using MongoDB first we need to run our MongoDB server using the below command
 
$ mongod
 
Once we see our server is running now we are required to create database. So quickly move into a new terminal tab and run the below command for creating a database  using MongoDB.
  • $ mongo
  • $ use todo
Once we are done now we need to connect our MongoDB with our MEANjs application.
 
Note

Don’t stop the MongoDB server otherwise it won’t get connected with our MEANjs application. 
 
Step 8 - Connecting to MongoDB
 
To connect first we need to call the mongodb library used by the express.
 
So let's install the mongoose library
 
$ npm install mongoose –save
 
This will install mongoose and will add it to the package.json file.
 
Step 9
 
Installing Body-Parser to parse middleware.
 
Use the below command to install.
 
$ npm install body-parser --save
 
Step 10
 
Working with Backend.
 
Now we will work with our server.js file.
 
In this file we will do the following things.
  • Connection request to mongodb
  • Create a Model to store our daily task
  • Work HTTP GET, POST and DELETE method
  • Configure our app to use stactic files and body-parser
Todo/server.js
  1. //calling express library    
  2. var express = require('express');    
  3. var app = express();    
  4. var bodyparser = require('body-parser');    
  5. var mongoose = require('mongoose');    
  6.     
  7. //connecting to MongoDB    
  8. mongoose.connect('mongodb://127.0.0.1:27017/todo');    
  9.     
  10. //creating model    
  11. var TaskSchema = mongoose.Schema({    
  12.     task: {type:String}    
  13. }, {collection: 'task'});    
  14.     
  15. var TaskModel = mongoose.model("TaskModel", TaskSchema);    
  16.     
  17. //configure app    
  18. app.use('/app', express.static(__dirname + '/app')); //use static file    
  19. app.use(bodyparser.json()); // for parsing application/json    
  20. app.use(bodyparser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded    
  21.     
  22. //GET request     
  23. app.get('/'function(req, res){    
  24.     res.sendfile('app/index.html');    
  25. });    
  26.     
  27. //POST request to save todo task in database    
  28. app.post("/api/create/todo", createTodo);    
  29. function createTodo(req, res) {    
  30.     var todoTask = req.body;    
  31.     //console.log(todoTask);    
  32.         
  33.     //save the todoTask in db    
  34.     TaskModel    
  35.         .create(todoTask)    
  36.         .then(    
  37.             function (success) {    
  38.                 console.log('Success');    
  39.             },    
  40.             function (error) {    
  41.                 console.log('Error');    
  42.             }    
  43.         )    
  44.         
  45.     res.json(todoTask);    
  46. }    
  47. //GET all task    
  48. app.get("/api/get/tasks", getAllTasks);    
  49. function getAllTasks(req, res) {    
  50.     TaskModel    
  51.     .find()    
  52.     .then(    
  53.         function (tasks) {    
  54.             res.json(tasks);    
  55.         },    
  56.         function (err) {    
  57.             res.sendStatus(400);    
  58.         });    
  59. }    
  60.     
  61. //DELETE task    
  62. app.delete("/api/delete/task/:id", deleteTask);    
  63. function deleteTask(req, res) {    
  64.     var taskId = req.params.id;    
  65.     //console.log(taskId);    
  66.     TaskModel    
  67.     .remove({_id: mongoose.Types.ObjectId(taskId)})    
  68.         .then(function () {    
  69.             res.sendStatus(200);    
  70.         },    
  71.         function () {    
  72.             res.sendStatus(400)    
  73.         });    
  74. }    
  75. app.listen('8080'function(){    
  76.     console.log('Server Running!!');    
  77. });   
Step 11
 
Now let’s run our Todo MEANjs Application.
 
To run we know which command we have to use
 
$ node server.js
 
Now create tasks, check the completed task, and delete.
 
Thank You!!