You are currently viewing NodeJS, Express, Mongoose and MongoDB RESTful Web Service – POST Request [Part 1]

NodeJS, Express, Mongoose and MongoDB RESTful Web Service – POST Request [Part 1]

Hey guys, recently I get a chance to explore Nodejs and Express, in my opinion, I think NodeJS and Express is a great option for building restful web services because its easy, fast and you don’t have to learn a new language, you can write the javascript code to build the restful API’s. So in this post, I will walk you through in making HTTP POST requests using Nodejs, Express, Mongoose, and MongoDB. Yes, you heard me right, we will connect to the MongoDB database, and save the data in the database. So let’s begin…




Tools and Technologies Used


  • NodeJS – 12.18.1
  • Npm – 6.14.5
  • Express – 4.17.1
  • Mongoose – 5.9.27
  • MongoDB – 4.4.0
  • Robo3T – 1.3 (Client application to connect to Mongo database)
  • Visual studio code
  • Postman (Rest client)

Install MongoDB and Robo 3T


Well, MongoDB is a NoSQL database and Robo 3t is a client application/GUI application to connect MongoDB so it’s like MySQL workbench where you will connect to MySQL server. Installation is pretty straight forward, just follow the instructions and you all set to use MongoDB.

Reference links to download the software

Once you install the software, make sure to start the MongoDB, you can start the database using the below command, To do that first you need to navigate to the installation directory and navigate to bin directory then run the below command

mongod --dbpath=<path to store the database>

Ex: mongod –dbpath=/Users/bushansirgur/downloads/mongodb-database




Next, open Robo 3T and create a new connection

Once you provide all the necessary information, you can test your connection by clicking on the test button, if everything is correct then Robo 3t, shows the success message. Next, you can connect to database using the connect button.

What are we building?


We will be building blogging applications, users can create a blog, update a blog, read all blogs/single blog and delete a blog. So in this post, let’s discuss how to create a blog by making HTTP POST requests.

Create a project


In your computer, where you want to create a project, go to that directory and create a folder with the name blogging-app.

Next, open that folder inside the visual studio code, or you can use any other text editors like sublime, brackets, or atom. I will be using VS code throughout this example.

Initializing npm

Our Node.js application needs to initialize npm before npm can be used. You can run npm init from the root of your project to get that done. That command will ask you a series of questions about the project and it’ll use the information to generate a package.json file at the root of your project.

{
  "name": "blogging-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
Installing an npm Module

You’re now ready to install an npm module. This is done using the npm command which was set up when Node.js was installed. You can use npm install to install a new module in your project. we will install 3 modules, express, mongoose, and nodemon. Execute the following modules from the root of the application.




To install express, execute the following command –

npm install express

To install mongoose, execute the following command –

npm install mongoose

To install nodemon, execute the following command –

npm install nodemon --save-dev

Notice, we are adding –save-dev, which means it will install nodemon as a dev dependency.

This command does three important things –

First, it creates a node_modules directory. npm uses this directory to store all the code for the npm modules you have installed.

Second, npm adds the module as a dependency by listing it in the dependencies property in package.json. This allows you to track and manage the module you have installed.

Third, npm creates a package-lock.json file. This includes detailed information about the modules you’ve installed which helps keep things fast and secure.

You should never make changes to node_modules or package-lock.json. Both are managed by npm and will get changed as you run npm commands from the terminal.

Next, update dev script to run the node application,

"scripts": {
    "dev": "nodemon src/index.js"
}

Once you update the dev script, our final package.json file looks like this –

{
  "name": "blogging-app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "nodemon": "^2.0.4"
  },
  "dependencies": {
    "express": "^4.17.1",
    "mongoose": "^5.9.27"
  }
}

Before start creating the rest endpoint, let’s look at the project structure once –

Connect to MongoDB from Mongoose


Like the MongoDB native driver, Mongoose provides a connect() function you can use to connect to your MongoDB database. So open mongoose.js and write the following code –

const mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/blog-app', {
    useNewUrlParser: true,
    useCreateIndex: true
})

At the very first line, we are importing the mongoose module using require() method. Next, we are calling connect() to establish a connection. Notice we are specifying the database name blog-app, which we haven’t created in MongoDB, and we don’t need to. The database will automatically create if it does not exist when we first insert a document.




Define a Schema


Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection. open models/blog.js file and add the following code to define a Schema.

const mongoose = require('mongoose');

const blogSchema = new mongoose.Schema({
    title: {
        type: String
    },
    subTitle: {
        type: String
    },
    description: {
        type: String
    }
}, { timestamps: {
        createdAt: 'created_at',
        updatedAt: 'updated_at'
    }
})

Create a Model


To use our schema definition, we need to convert our blogSchema into a Model we can work with. To do so, we pass it into a mongoose.model(modelName, schema)

const Blog = mongoose.model('Blog', blogSchema);

Following is the final code which is present in models/blog.js file

const mongoose = require('mongoose');

const blogSchema = new mongoose.Schema({
    title: {
        type: String
    },
    subTitle: {
        type: String
    },
    description: {
        type: String
    }
}, { timestamps: {
        createdAt: 'created_at',
        updatedAt: 'updated_at'
    }
})

const Blog = mongoose.model('Blog', blogSchema);

module.exports = Blog;

Create separate Routers


Express allows us to create as many routers as we want. These separate routers can then be combined into a single Express application. You can create a new router using express.Router() as shown below. The code below creates the router, adds routes, and exports the router from the file. Open routers/blog.js file and add the following code




const express = require('express');
const router = new express.Router();
const Blog = require('../models/blog');

router.post('/blogs', (req, res) => {
    
    const blog = new Blog(req.body);
    blog.save().then((blog) => {
        res.status(201).send(blog);
    }).catch((error) => {
        res.status(400).send(error);
    })
    
})

module.exports = router;

The code above uses router.post() to set up a POST request handler for /blogs. The handler function creates a new instance of the blog model and saves it to the database.

Create a Webserver


Next, import module express. You get access to a single function express() you can call to create a new Express application. express.json() is also set up to parse incoming JSON into a JavaScript object which you can access on req.body. The last thing to do is to start the server. This is done by calling app.listen() with the port you want to listen to. Open index.js file and add the following code.

require('./db/mongoose');
const express = require('express');
const blogRouter = require('./routers/blog');

const app = express();
const port = 3000;

app.use(express.json());
app.use(blogRouter);

app.listen(port, () => {
    console.log('App is running on port 3000!');
});

That’s it, now let’s run the application – go to the root of the application and run the following command

npm run dev

This will start the application on the port localhost:3000. Now, let’s open a postman and test our work.






That’s it for now, I hope you guys understood something. If you like this post, please share this with your friends and colleagues. In the next post, we will discuss how to make HTTP GET request to read all the documents from MongoDB. I will see you in the next post.

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

This Post Has 2 Comments

  1. Abbas

    ‘hi
    This is Abbas you are doing great job……and you are to help ful and favourable man

  2. backlink tay

    Just what I was looking for, appreciate it for
    putting up.

Leave a Reply to Abbas Cancel reply