Creating a MERN stack application: Part 1 – The Backend(Express Js)

Prerequisites:

  • Basic understanding of Node.js and JavaScript.
  • Node.js v10+ and a Node.js package manager installed locally, such as npm.

Create a project directory named mern-stack-app

Using the terminal, make that directory your current directory and execute the following command to initialize your Node.js project with default settings:

npm init -y

Then, under the project directory, create the entry point of the application, a file named index.js.

We are now ready to add dependencies to our project:

npm install express body-parser cors mongoose

Let’s take a quick look at the four packages:

  • express: Express is a fast and lightweight web framework for Node.js. Express is an essential part of the MERN stack.
  • body-parser: Node.js body parsing middleware.
  • cors: CORS is a node.js package for providing an Express middleware that can be used to enable CORS with various options. Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.
  • mongoose: A Node.js framework which lets us access MongoDB in an object-oriented way.

Install nodemon as a global development dependency, this monitors your project source code and automatically restart your Node.js server whenever it changes.

sudo npm install -g nodemon

Edit the package.json file to run nodemon

{
  "name": "mern-stack-app",
  "version": "1.0.0",
  "description": "MERN stack application",
  "main": "index.js",
  "scripts": {
    "start": "nodemon index.js",
    "dev": "nodemon index.js"
  },
  "author": "Luciekimotho",
  "license": "ISC",
  "dependencies": {
     "nodemon": "^1.19.3"
  }
}

Open the index.js file and insert the following basic Node.js / Express server implementation:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const PORT = 8080;
app.use(cors());
app.use(bodyParser.json());
app.listen(PORT, function() {
    console.log("Server is running on Port: " + PORT);
});

With this code we’re creating an Express server, attaching the cors and body-parser middleware and making the server listening on port 8080.

Start the server by using nodemon:

nodemon server

You should now see an output similar to the following:

Setting up the MongoDB database

Prerequisite:

Should have MongoDB installed, if not use this link to install MongoDB on Ubuntu

The next step is to create the MongoDB database instance. Therefore we’re connecting to the database server by using the MondoDB client on the command line:

$ mongo

Once the client is started it prompts you to enter database commands. By using the following command we’re creating a new database with the name vms:

use vms

Now we connect to our newly created database using mongoose, edit the index.js file

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const PORT = 8080;
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://127.0.0.1:27017/mern', { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
    console.log("MongoDB database connection established successfully");
})
app.listen(PORT, function() {
    console.log("Server is running on Port: " + PORT);
});

On the console you should now also see the output MongoDB database connection established successfully in addition.

Create a Mongoose Schema

By using Mongoose we’re able to access the MongoDB database in an object-oriented way. This means that we need to add a Mongoose schema for our Visitor entity

Inside the back-end project folder create a new file visitor.model.js and insert the following lines of code to create a Visitor schema:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Visitor = new Schema({
    name: {
        type: String
    },
    phone_number: {
        type: Number
    },
    id_number: {
        type: Number
    },
    location: {
        type: String
    }
});
module.exports = mongoose.model('Visitor', Visitor);

https://codingthesmartway.com/the-mern-stack-tutorial-building-a-react-crud-application-from-start-to-finish-part-1/

Leave a Reply

Your email address will not be published. Required fields are marked *