
Today we will be talking about the back-end of our project.As I mentioned before i will be using Mongo Atlas for this project so, lets being with that.
Database Creation
- Create an account on Cloud Mongo

- After creating an account, lets create our first project.

- Select proper configuration for your project
- Select one provider
- Select the nearest region
- Leave everything as it is
- Finally create cluster

- Finally after waiting for a bit you will be on the following screen

- Great you have created your first cluster now we will get connection details, by clicking on connect
- I will be whitelisting all the connections.(but if u don’t want to then don’t.)
- Create a user ( I will be creating an admin user)
- Be sure to remember the password as we will be using it in next part.
- Chose “Connect your application”
- Finally click on copy it will copy the connection string.


Back-End
Now we will be working on our back-end, we will be creating a REST-Api to do modify our MongoDb. So lets start with the coding ❤
We will only be working in /backend folder so all the path will be relative to it.
- In terminal
touch .env server.js
mkdir routes models
touch routes/task.js models/task.model.js
Here we are creating an .env file where we will be storing environment variables (in our case MongoDb URI) , then we will create an entry point for the project which will handle everything i.e server.js
Then we are creating our routes i.e our All CRUD functions related to “task” are are made in this file, for a bigger project we may more than one route. Finally we will create a model for a task, i.e schema for our “Task” model that using mongoose package.
- In .env
- Past the Connection string
- change <password> with the password u gave before and for <dbname> change it to tasks
MONGO_URI="mongodb+srv://admin:<password>@cluster0.iayan.mongodb.net/<dbname>?retryWrites=true&w=majority"
This just a connection string that tells mongoose the basic info for our database, like where the server is , which user is connecting to server, and the database name
- In server.js
const express = require('express')
const cors = require('cors')
require('dotenv').config()
const app = express()
const port = process.env.PORT || 5000
app.use(cors())
app.use(express.json())
app.listen(port, () => {
console.log(`Server is running on PORT: ${port}`)
})
Here we are first importing the packages required by our express back-end, like express and cors. To retrieve our read .env file we our loading the variables in it using require('dotenv').config()
Then we will be create an instance of express() , and add cors, and express.json.
Cors here is used since we will be using react as front-end so we don’t have any problems with resource sharing between too sources and express.json, tells express that all the requests will be in json format.
Finally using app.listen() we tell express to listen all requests coming on the specified port.
- We will now connect to MongoDB in server.js too
#...after app.user(express.json())
const mongoose = require('mongoose')
const uri = process.env.MONGO_URI
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
})
const connection = mongoose.connection
connection.once('open', () => {
console.log("MongoDB connected")
})
#...
Here we will be connecting our back-end with MongoDB using mongoose package.
Using MONGO_URI in our .env we will be connecting to database with ht method .connect(uri, options)
- Lets start creating our Task model for MongoDb
- In ~/models/task.model.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const taskSchema = new Schema({
taskName: {
type: String,
required: true,
unique: true,
trim: true,
minLength: 3
},
createdAt: {
type: Date,
required: true
},
status: {
type: String,
required: true,
trim: true,
}
}, {
timestamps: true,
})
const Tasks = mongoose.model('Task', taskSchema)
module.exports = Tasks
Here we are simple creating an schema for our mongo-document, basically every document that we create should follow this else it will give an error.
The fields we will be creating here are –
- id = unique id of document , it automatically generated
- TaskName = unique name for task that we will be providing
- CreatedAt = basically when the task was created
- Status = what is the current status of task
- timestamps = adds an updatedAt field to the document
Then we create an model object using the schema which is exported.
- Creating Rest-Api for our CRUD app is very simple,using express.
- We will be creating the route for tasks now , in ~/routes/task.js
const router = require('express').Router()
const Tasks = require('../models/task.model')
router.route('/').get((req, res) => {
Tasks.find()
.then(task => {
res.json(task)
})
.catch(err => {
console.error(err)
res.status(400).json({ error: `${err}` })
})
})
router.route('/').post((req, res) => {
const taskName = req.body.taskName
const createdAt = Date.now()
const status = req.body.status
const newTask = new Tasks({
taskName,
createdAt,
status,
})
newTask.save()
.then(() => res.json('Exercise added'))
.catch(err => {
console.error(err)
res.status(400).json({ error: `${err}` })
})
})
module.exports = router
Here we are creating an express router, (router is basically how applications endpoints respond to client requests.)
We start by making two routes ,GET route to get all the tasks in database and a POST route to create a TASK and add it to database.
I am assuming GET route is pretty self explanatory , here whenever we get a request on the ‘/’ end point we use our TASK model to retrieve all the documents in task table using .find() method of model .
Finally in the POST route, we are reading the body of the request and extracting the taskName,status from it, then creating an TASK object with the parameters, and using the .save() method we are adding it our database.
- Now lets test our basic routes that we created, but first lets add this route to our app in server.js
#... after Mongo connection
const taskRouter = require('./routes/task')
app.use('/tasks',taskRouter)
Here we are just adding the router we made to our express app
- Now lets test out our basic back-end routes , I will be using Postman for checking the api.
- Lets start our test server, in terminal
nodemon server.js
If you did everything right your terminal might look something like this
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Server is running on PORT: 5000
MongoDB connected
- We will start by creating a task
- By sending a POST request to http://localhost:5000/tasks
- We will be sending taskName and status in body with the request

Here we are we are creating an TASK using post method on the endpoint /tasks as specified above . We add taskName and status to the body of our request since that is what will be required by the route we defined earlier else it will create an error. Finally on sending the request if we setup the server right we will get the following output.

- Lets check if it was added to database, but we wont be going to mongoDB to check it we will be using GET method we made for our tasks route to check the tasks.

- Now we will be adding more routes to our api , because we are creating a CRUD api we need to have update and delete routes too
- In ~/routes/task.js
#...after the post method
router.route('/:id').delete((req, res) => {
Tasks.findByIdAndDelete(req.params.id)
.then(() => {
res.json({ message: 'Task deleted' })
})
.catch(err => {
console.error(err)
res.status(400).json({ error: `${err}` })
})
})
router.route('/:id/update').post((req, res) => {
Tasks.findByIdAndUpdate(req.params.id, {
taskName: req.body.taskName,
status: req.body.status
})
.then(() => {
res.json({ message: `Task updated` })
})
.catch(err => {
console.error(err)
res.status(400).json({ error: `${err}` })
})
})
Here we are creating two new routes i.e ‘/:id’ which is a delete request and ‘/:id/update’ which is a post request, here id is the id of document that we created that is automatically generated.
To delete we are using Model.findByIdAndDelete(id) to delete the document from mongodb, to update we are using Model.findByIdAndUpdate(id,updates) to update the document, here also we be using extracting the data from the body of the request to update the document.
- Testing new routes
- Update task

- Checking if it worked using GET

- Deleting the task


Conclusion
Today we learnt how to use express to create REST-Api, using which we created the back-end of for our application that does CRUD operations on a MongoDb.
The code is available at this link.





