What is Express?
Express is a light-weight web application framework used to develop web and mobile application fast and easy. Express act as a middle-ware used to respond any HTTP requests received from the client application. It is used to define the routing table to perform various action based on HTTP methods and URL’s.
What is MongoDB and mongoose?
MongoDB is a document-oriented NoSQL database used to handle high volume of data storage. Scalability and flexibility are the key feature of MongoDB.
Mongoose is a client API of node.js used to connect the database from Express JS.
In this post, we are going to see how to insert a record in MongoDB using postman specific API client request. Express is a middle-ware used to process the incoming request from postman client tool and insert in the MongoDB.
Pre-Requisites (Windows OS):
- Install Node.js latest LTS Version: 12.18.3 (Check the node version & npm version in cmd prompt using the command node -v and npm -v)
- Install any latest freeware version of Microsoft visual studio code (v1.47) – IDE
- Install latest MongoDB community edition v1.21 in your windows machine
Steps to follow;
- Create a project directory/folder named as ‘expresspost’ in your windows machine
- Open the step-1 created project folder in Microsoft VS Code IDE
- Ensure terminal window showing the project directory path in VS Code IDE
- Initialize using npm command in the terminal window associated with VS Code IDE
>npm init
- Ensure Package.json file has been created
- Install express using npm command as follows;
>npm install express –save
- Install mongoose client in your windows machine using below command
>npm install mongoose –save
- Install body-parser used to parse the incoming request triggered from client API;
>npm install body-parser –save
What is body parser?
It is used to parse the incoming data from any format right from from text, json etc. we are importing the body parser module using the npm command.
Create server.js file using the below code snippets which is used to process the incoming request using the modules such as routing, model and db connection;
const express = require(‘express’);
const mongoose = require(‘mongoose’);
const bodyParser = require(‘body-parser’);
const app = express();
// server port has been declared
const PORT = process.env.PORT || 3000
const config = require(‘./backend’);
const Routers = require(‘./Routers’);
mongoose.connect(config.DB, { useUnifiedTopology: true,useNewUrlParser: true }).then(
() => {console.log(‘Database is connected’) },
err => { console.log(‘Not able to connect the database’+ err)}
);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(‘/user’, Routers);
app.listen(PORT, () => {
console.log(‘Server is UP and running on PORT:’,PORT);
});
Create backend.js file used to declare the MongoDB connection;
// connect the collection name
module.exports = {
DB: ‘mongodb://localhost:27017/express’
}
Create users.js file which is a data layer to insert records in MongoDB;
const mongoose = require(‘mongoose’);
const Schema = mongoose.Schema;
const User = new Schema({
name: {
type: String
},
email: {
type: String
},
address: {
type: String
}
},{
collection: ‘users’
});
module.exports = mongoose.model(‘User’, User);
Create Routers.js file used to handle the POST request from Postman;
const express = require(‘express’);
const Routers = express.Router();
const User = require(‘./users’);
Routers.route(‘/add’).post(function (req, res) {
const user = new User(req.body);
console.log(user);
user.save()
.then(user => {
res.json(‘User details added successfully.’);
})
.catch(err => {
res.status(400).send(“Unable to add user details in database.”);
});
});
module.exports = Routers;
All SET!!! Now make node server UP and running using the below command;
>npm start
Please trigger a post request using postman with JSON format;
{
“name”: “robert”,
“email”: “robert@gmail.com”,
“address”: “10, Wendy Street, North East Zone, California 90201”
}
API endpoint should be http://localhost:3000/user/add
GitHub Repo URL: https://github.com/gopekanna/express
Thank you!!!