Serverside for CRUD using MERN stack -Part 2

Sachindu Gimhana
4 min readMar 9, 2021

In this blog, I am going to work on the backend of our application. First, we will use MongoDB Atlas for the MERN database setup.

Creating a database connection using MongoDB Atlas

MongoDB Atlas is the global cloud database service for modern applications.

First, we need an account. Create one and follow these steps. After creating an account, we can see something as follow:

When you click on the ITP section, you can see a button called +New Project. Clicking that button you can create a new project.

After clicking on the Build a Cluster button you can choose the cluster that you wanted. At the bottom, you can change the Cluster name. Then click on the Create Cluster button.

Now you can see your cluster as follow:

Go to COLLECTIONS and click on Add My Own Data button. Then give a name to the database and the collection.

Then click on the CONNECT button and fill in the username and password form for your database.

Now click the Create MongoDB User button. You can also choose either your current IP address or a different IP address, it’s your choice.

Then, if you follow the Choose a connection method button, you will see some different methods as follow:

Here, choose the Connect your application method. Now you will get your database link as follow:

Your database is ready. Now we need to add it to our project.

Update your server.jswith this:

const express = require(‘express’);
const app = express();
const bodyParser = require(‘body-parser’);
const cors = require(‘cors’);
const mongoose = require(‘mongoose’);
const PORT = 5058;
app.use(cors());
app.use(bodyParser.json());
mongoose.connect(‘mongodb+srv://Sachindu<password>@crud.par7a.mongodb.net/myFirstDatabase?retryWrites=true&w=majority’, {
useNewUrlParser: true });
//Replace <password> with your database password
const connection = mongoose.connection;
connection.once(‘open’, function(){
console.log(“Mongo database connection established succesfully”);
})
app.listen(PORT, function(){
console.log(“Server is running on port : “ + PORT);
});

Now you can see our database connection established successfully.

Building RESTful APIs

Database model

To interact with our database, we need to create a model. So, create a file called model.js in the root and update it with this:

const mongoose = require(‘mongoose’);
const Schema = mongoose.Schema;
let User = new Schema({ First_Name: {
type: String,
required: true,
trim: true,
},
Last_Name: {
type: String,
required: true,
trim: true,
},
Email_Address: {
type: String,
required: true,
trim: true,
lowercase: true,
},
Mobile_Number:{
type: String,
required: true,
trim: true,
maxlength: 10,
},
Home_Address:{
type: String,
required: true,
trim: true,
}
});
module.exports = mongoose.model(‘users’, User);

Now we have to bring our model to server.js file and attach endpoints to our server by using express. Update server.js with this:

const userRoutes = express.Router();

let User = require('./model);

If you want to create a separate file for routes. It’s fine. But I implemented my routes in my server.jsfile as follow:

const express = require(‘express’);
const app = express();
const bodyParser = require(‘body-parser’);
const cors = require(‘cors’);
const mongoose = require(‘mongoose’);
const userRoutes = express.Router();
const PORT = 5058;
let User = require(‘./model’);app.use(cors());
app.use(bodyParser.json());
mongoose.connect(‘mongodb+srv://Sachindu:<password>@crud.par7a.mongodb.net/myFirstDatabase?retryWrites=true&w=majority’, { useNewUrlParser: true });
//Replace <password> with your database password
const connection = mongoose.connection;connection.once(‘open’, function(){
console.log(“Mongo database connection established succesfully”);
})
userRoutes.route(‘/’).get(function(req, res) {
User.find(function(err, users) {
if(err) {
console.log(err);
}else {
res.json(users);
}
});
});
userRoutes.route(‘/:id’).get(function(req, res){
let id = req.params.id;
User.findById(id, function(err, user){
res.json(user);
});
});
userRoutes.route(‘/add’).post(function(req, res){
let user = new User(req.body);
user.save()
.then(user => {
res.status(200).json({‘user’: ‘user added successfully’});
})
.catch(err => {
res.status(400).send(‘adding new user failed’);
});
});
userRoutes.route(‘/update/:id’).post(function(req, res) {
User.findById(req.params.id, function(err, user) {
if (!user)
res.status(404).send(‘data is not found’);
else
user.First_Name = req.body.First_Name;
user.Last_Name = req.body.Last_Name;
user.Email_Address = req.body.Email_Address;
user.Mobile_Number = req.body.Mobile_Number;
user.Home_Address = req.body.Home_Address;
user.save().then(user => {
res.json(‘User updated’);
})
.catch(err => {
res.status(400).send(“Update not possible”);
});
});
});
userRoutes.route(‘/:id’).delete(function(req, res) {
User.findByIdAndDelete(req.params.id)
.then(() => res.json(‘Data is deleted!’))
.catch(err => res.status(400).json(‘Error: ‘ + err));
});
app.use(‘/users’, userRoutes);app.listen(PORT, function(){
console.log(“Server is running on port : “ + PORT);
});

Run the project to see if everything is fine at this moment

Conclusion

You can test all APIs through Postman.

Stay tuned. Thank you!

--

--