Getting Started With MERN stack: Creating ToDo App Backend in MERN - ByteScout
  • Home
  • /
  • Blog
  • /
  • Getting Started With MERN stack: Creating ToDo App Backend in MERN

Getting Started With MERN stack: Creating ToDo App Backend in MERN

Are you looking to build your first application using the MERN stack? If yes, then you have come to the right place.

As a web developer, you always need to learn new technologies. MERN has recently started to catch attention from the startup community. If you are an agile developer, then MERN is for you!

Let’s get started.

What is MERN?

MERN stands for MongoDB, Express, React and Node.js. It is a technology “stack” that consists of tools and frameworks so that you can do end-to-end development. A stack works closely with each other so that you can take benefit from their synergy.

Other key widely used web development stacks include LAMP(Linux, Apache, MySQL, PHP) and MEAN(MongoDB, ExpressJS, AngularJS, NodeJS).

In MERN stack, React takes care of client-side/frontend, whereas the expressJS takes care of the server-side/backend. Lastly, we have MongoDB, the database that supports the No-SQL, a document-oriented approach. Nodejs is a JavaScript runtime environment that enables JavaScript to run on a machine.

Getting Started With MERN stack: Building your first application

In this tutorial, we are going to create a simple todo application backend using the MERN stack.

Before we get started, we need to list the pre-requisite for the project.

Prerequisites

To get started, you need two things: nodeJS and npm. Installing them can take quite some command and hence we encourage you to their respective site to install them.

We will also be using Ubuntu for the tutorial. If you have Windows, you can also follow the tutorial. All you need to do is do basic things based on your operating system.

Lastly, we need a code editor that can highlight JavaScript.

Code Setup

With our pre-requisite installed, it now does our application code setup.

Let’s create a folder named, TodoApp using the command below.

mkdir TodoApp

Now, to get into the created directory, use the cd command.

cd TodoApp

Once you are inside the folder, you need to initialize the folder using the npm command.

npm init

This will walk you through the instructions to set up the application. If you want default settings to work for your application, then you need to use npm init – y instead of just npm init.

If you did everything correctly, it would create a file named, package.json

Start MERN Programming

Server Setup

For our TodoApp application, we need to run a server. You can create a server in two ways: first is to use the HTTP module that is inbuilt within the node. Another way is to use the expressJS framework. As we are using the MERN stack, we are going to use the expressJS framework for creating our server.

Let’s setup express below.

npm install express

Start MERN Development

Now, your project folder should have two files and one folder.

  • node_modules folder
  • JSON
  • package-lock.json

Next, we need to create an index.js file for our project. In the index.js file, you need to put in the following code.

const express = require('express');
require('dotenv').config();

const app = express();

const port = process.env.PORT || 5000;

app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});

app.use((req, res, next) => {
res.send('Welcome to Express');
});

app.listen(port, () => {
console.log(`Server running on port ${port}`)
});

We also need to add the following code so that it fixes the Cross-Origin Resource Sharing(CORS). It generally happens when you try to access the app’s API across different domains.

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

Now, it is time for us to save the index.js file and run the server. To run the server, use the following code.

node index.js

There is a chance that you can get an error, cannot find module ‘dotenv’, then you need to install the npm module using the command below.

npm install dotenv

Programming MERN
Getting an error and solving it

Now, rerun the node index.js command and you should be able to receive the following message.

Server running on port 5000

Routes

Our next step is to create routes for our app. These routes are required to perform actions for our app. In the case of a ToDo app, we need to create routes for three actions.

  • View the Todo tasks
  • Create a Todo task
  • Delete a Todo task

Routes are a way to create endpoints for the app.

First, we will create a routes directory.

mkdir routes

Next, create an api.js files within the routes folder.

cd routes

gedit api.js

Once the file is created, now copy-paste the code as shown below.

const express = require ('express');
const router = express.Router();
router.delete('/todos/:id', (req, res, next) => {
})
router.get('/todos', (req, res, next) => {
});
router.post('/todos', (req, res, next) => {
});
module.exports = router;

The above code is self-explanatory.

Models

Awesome! We now have our servers and routes ready; it is time for us to create Models for our TodoApp, powered by MERN stack.

Models are used if you use MongoDB. Along with the models, we also need to create a schema. This is needed as MongoDB is a NoSQL database.

But, why do we need schema?

Schema is a blueprint that will enable you to construct the database. It lets you define fields in each document. Moreover, you can also set default values and also provide a validation requirement for them.

Apart from that, you can also define the instance and static helper methods. It lets you work easily with different datatypes.

We are going to use the mongoose –  node package that lets you work with MongoDB easier.

npm install mongoose

Once installed, we now need to create the models directory and then create a todo.js file within it.

mkdir models

cd models

gedit todo.js

Now, copy and paste the following code in the todo.js file.

const mongoose = require(‘mongoose’);
const Schema = mongoose.Schema;

//create schema for todoApp
const TodoAppSchema = new Schema({
  action: {
    type: String,
    required: [true, 'This field is required']
  }
})

//create model for todoApp
const TodoApp = mongoose.model('todo', TodoSchema);

module.exports = TodoApp;

Going back to Routes

If you remember, our routes file, api.js is not yet completed. As we have completed our models, it is now time to write our api.js file according to it.

Here at the top, we will link the model file we created.

const TodoApp = require(‘../models/todo’);

The get function of the router will be defined as below.

 

router.get('/todos', (req, res, next) => {
  //exposing the data and action fields
  Todo.find({}, 'action')
    .then(data => res.json(data))
    .catch(next)
});

Our post function will be as below.

router.post('/todos', (req, res, next) => {
  if(req.body.action){
    Todo.create(req.body)
      .then(data => res.json(data))
      .catch(next)
  }else {
    res.json({
      error: "Input field is empty, please enter something"
    })
  }
});

And, lastly the delete router function as below.

router.delete('/todos/:id', (req, res, next) => {
  Todo.findOneAndDelete({"_id": req.params.id})
    .then(data => res.json(data))
    .catch(next)
})

Getting our Database ready

We have made a lot of progress until now. We have completed writing our routers, models and also making the server work. Now, it is time for the database to work.

Database creation and configuration is always a long process. That’s why we recommend you to use mlab to do it. You can read here on how to do it.

Once you have set it up correctly, it is now time to add the database code to the index.js file. Simply add the code below to the index.js file and we are good to go!

const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const routes = require('./routes/api');
const path = require('path');

//Setting up database connection
mongoose.connect(process.env.DB, { useNewUrlParser: true })
  .then(() => console.log(`The Database is connected successfully`))
  .catch(err => console.log(err));

//using node’s promise because mongoose promise is depreciated
mongoose.Promise = global.Promise;

app.use(bodyParser.json());

app.use('/api', routes);

app.use((err, req, res, next) => {
  console.log(err);
  next();
});

Accessing environmental variables

Lastly, we need to now create a .env file at the application core folder so that we can access environmental variables with process.env.

Once you create the file, you need to provide the mlab database credentials including username and password.

DB = ‘mongodb://<USER\>:<PASSWORD\>@ds039950.mlab.com:39950/todo’

Testing API and Conclusion

We have successfully created the backend part of our TodoApp. Now, you need to test APIs using Insomnia and Postman or another testing client from here.

From here, you need to learn how to use react and create the frontend. We leave it up to you so that you can use your creativity in designing the app.

Did you find the tutorial useful? If you do, then comment below let us know.

   

About the Author

ByteScout Team ByteScout Team of Writers ByteScout has a team of professional writers proficient in different technical topics. We select the best writers to cover interesting and trending topics for our readers. We love developers and we hope our articles help you learn about programming and programmers.  
prev
next