Getting Started with MERN Stack (Part – 2)

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

  • 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

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.

Getting Started with MERN Stack (Part – 1)

MERN Stack is a Javascript Stack that is used for easier and faster deployment of full-stack web applications. MERN Stack comprises of 4 technologies namely: MongoDBExpressReact and Node.js. It is designed to make the development process smoother and easier. It is one of the most simplest stacks one can learn, and a good one to start with to understand full stack development.

Componentes

  • Mongodb

A document-oriented, No-SQL database used to store the application data.For the project we will be using Mongo-Atlas, you can use a local mongo server also.

  • ExpressJs

A framework layered on top of NodeJS, used to build the backend of a site using NodeJS functions and structures. Since NodeJS was not developed to make websites but rather run JavaScript on a machine, ExpressJS was developed.

  • React

A library created by Facebook. It is used to build UI components that create the user interface of the single page web application. We will be using create-react-app to here create a react app with no configuration.

  • Nodejs

The JavaScript runtime environment. It is used to run JavaScript on a machine rather than in a browser.

Setup

I am assuming You have installed nodejs and git installed.

  • Project
mkdir to-do-app
cd mern-to-do-app
npm init
sudo npm install -g concurrently

As the start of any project we first make the directory.Then we initialize a node project and install a package concurrently, we use concurrently to run our backend and frontend simultaneously. We will go in detail later.

  • Frontend – React
sudo npm -g create-react-app 
npx create-react-app frontend

We will be using create-react-app to get a ready-made react app that creates the frontend build pipeline. It doesn’t handle any backend or database logic , it uses babel and web-pack to do so but that is something we need to poke our heads in.

  • Backend
mkdir backend
cd backend
npm init
npm install express mongoose cors dotenv
npm install nodemon --save-dev

Finally, we will create a backend folder since it’s good practice to separate your frontend and backend so, we will also follow the norm. Here also we initialize a node project so its easier for us to manage packages this way. Then we will be installing the following packages

  • Express ( web-framework, we will be using it to handle our backend )
  • Cors (since our backend and frontend use different servers,cors helps to remove the differences)
  • Dot-env ( it loads environment variables from a “.env” file into process.env )
  • Mongoose (Not the animal :p , we will be using this to interact with our MongoDb)

You can remove files from frontend (refer below) since those files are made to display react template , since we will be creating not be using it we can delete those files.

Right now your project file structure should look something like this-

to-do-app
├── README.md
├── backend
│   ├── package-lock.json
│   └── package.json
├── frontend
│   ├── README.md
│   ├── package.json
│   ├── public
│   │   └── index.html
│   ├── src
│   │   ├── App.js
│   │   └── index.js
│   └── yarn.lock
├── package-lock.json
└── package.json

Or you can check the git and follow along.

Getting Started with Flask

Flask is a micro web framework written in Python, one of the most simple frameworks out there and easiest to start with.

To get started all u need to do is have python installed and type this.

  • terminal
pip install flask
touch app.py
  • app.py
from flask import Flask

app = Flask(__name__)


@app.route('/')
def index():
    return '<h1>Hello world </h1>'


if __name__ == "__main__":
    app.run()
  • terminal
flask run

So lets talk about what we did here

  • We installed flask with PIP, and created a file “app.py”.
  • Then in “app.py”,
    • We import Flask from flask and create a flask object
    • then using @app.route('/') we assign a route at ‘/’ to render the return statement i.e a simple html syntax of “Hello world”
    • Finally we used app.run() to start call our flask object and start the server
  • Finally using flask run we run our “app.py” (“app” is default FLASK_APP so no need to specify specific entry point ).

now if you click on the link or go to http://127.0.0.1:5000/ you will be greeted with

That’s all it takes to start a flask sever , obviously to master flask u will need spend countless hours and make a proper project, but then again

“Rome wasn’t built in a day”

WSL(Window-Subsystem-for-Linux)

When I first joined my college, I was asked to install Ubuntu because “THAT’S WHAT EVERYONE USES.” So obviously, I complied with the mainstream. With the help of YouTube 1 hr later I had dual-booted Ubuntu with windows (p.s only used it for couple days)

Now 2 years later the perfect solution was released by windows WSL-2

With WSL you can not only use Linux terminal but use windows without any problems

Installing WSL-2

In powershell enter this line-

dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

and restart your pc after this.

To make WSL-2 as default,type the following code in power-shell

wsl --set-default-version 2

After this you will see a line like “WSL 2 requires an update to its kernel component. For information please visit https://aka.ms/wsl2kernel ” just go to the website and install the msi on that site and re run the above code.

Viola you have installed WSL 2 in your PC.

Go to Microsoft Store and select your favorite Linux distribution.

  • Ubuntu 20.04 LTS
  • Ubuntu 18.04 LTS
  • Ubuntu 16.04 LTS
  • Kali Linux
  • Fedora Remix
  • Alpine
  • And many more…

Select any one or as many you want and install them, after that launch the newly installed app. You will be greeted with the following screen.

Enter you a username and password for the user, confirm the password and you are done.

If you did everything right you will be on this screen.

Design a site like this with WordPress.com
Get started