M

Mayur Nalwala

August 05 2022

CRUD app using Node.JS, Express & MongoDB - Part 2

#javaScript

#mongodb

#expressjs

#rest api

#mongoose

#nodemon

#mongodb compass

CRUD app using Node.JS, Express & MongoDB | Mayur Nalwala

In This Part :

  • We will structure our node application in a proper MVC Format.
  • Enable CORS, logger and Body Parser.
  • Try hitting out API with postman.
  • Create the rest of our API’s.

1. Structuring our application:

We will structure our existing node application and the route in a MVC Format.
M: Model, this will include all the code and schema for our database models.
V: View, this will include the website view i.e the layout. We will not cover the views here as we are designing API.
C: Controller, this will include the logic of how the app handles incoming requests and outgoing responses.
a simple CRUD app using Node.js, Express & MongoDB
Create the following sub-folders in BackEnd.
Models: In this folder create “Posts.js” for our DB Schema.
Routes: This folder will have “ PostsRoutes.js” file for our API routes.
Controllers: This folder will have “ PostController.js” file for the route functions.

The next steps can get a bit confusing so please be patient and carefully follow the steps.

We will start with Models:

Create a file “Posts.js” in Models folder, this will have our posts schema. Move the model/schema we created in “app.js” (in part one: here ) to “ Posts.js” along with the necessary imports.
// Models/Posts.js
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
// create posts schema -- // moved from app.js //
const PostsSchema = new mongoose.Schema({
title: {
type: String
},
author: {
type: String
},
desc: {
type: String
}
});
module.exports = mongoose.model('posts', PostsSchema);
app.js file after moving things in posts.js
// app.js
const express = require('express');
const app = express();
// create a base route with a response
app.get('/', (req,res) => {
res.send('server running');
})
app.get('/getPosts', (req, res) => {
const posts = await Posts.find();
res.json(posts);
})
module.exports = app
next in “ server.js” file require “ Posts.js” as follows. This has to be done before the “const app = require(‘./app’)” so that it is accessible throughout our application.
// server.js
const mongoose = require('mongoose');
require('dotenv').config({ path: '.env' });
// Database connection
mongoose.connect(process.env.DATABASE,
{
useUnifiedTopology: true,
useNewUrlParser: true
}
);
mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promises
mongoose.connection.on('error', (err) => {
console.error('Database Connection Error');
});
// require our models here so that it can be accessed throughtout the application
require('./Models/Posts');
// require app.js
const app = require('./app');
// start the server on port 3000
const server = app.listen(3000, () => {
console.log('Express running → PORT 3000');
})

Next, we structure our routes:

We configure our routes in “ PostsRoutes.js” with the help of express.Router().

Move the existing routes from “ app.js” to “ PostsRoutes.js” file. Import mongoose and initiate model we created (line number 4).
a simple CRUD app using Node.js, Express & MongoDB
next, we import our routes in “app.js” as follows.
a simple CRUD app using Node.js, Express & MongoDB
Further, we separate our controller functions: In “PostController.js” we move our controller functions from our routes file as follows.
a simple CRUD app using Node.js, Express & MongoDB
next, we import our “PostController.js” in “PostsRoutes.js” and use them as follows:
a simple CRUD app using Node.js, Express & MongoDB
That’s it, we are done with the structuring of our node applications. Open the terminal and run “npm start” and go to the routes to check our application running.
a simple CRUD app using Node.js, Express & MongoDB

Recap:

  • First, we moved our schema into a separate “Posts.js” file and imported that schema in “server.js”.
  • Next, we moved the routes to “PostsRoutes.js” and imported our routes in “app.js”.
  • Finally, we moved our router controller functions into “PostController.js” and imported the functions in “PostsRoutes.js”.

2. Enabling CORS, logger and bodyParser:

What is CORS: Cross-origin resource sharing (CORS) in simple terms is a mechanism that allows data to be requested from another domain (outside the domain from which the data is being served).

What is a Logger: Logger an HTTP request logger middleware for NodeJs. With the help of logger, we get to know what type of request our application is serving and what API is been hit or requested.

What is a Body Parser: Express can’t handle reading data or form data on its own, so Body Parser is used to parse data coming from the front-end or from any other application using our API.

Learn more about CORS , Logger , BodyParser

3. Next, let's try hitting out API via postman:

Postman is a great tool to test out our API’s, it gives us a very simple UI to work with and real scenarios can be tested here. You can learn more and download the app from the Official Site .
a simple CRUD app using Node.js, Express & MongoDB
Let’s try hitting getPosts API in postman:
a simple CRUD app using Node.js, Express & MongoDB
Select GET request from the dropdown and paste the URL and hit SEND, and there we have the response.

4. Next, let’s create the rest of the APIs:

Now we have our setup done let’s move forward and create the rest of the APIs and finish up the backend part.

Create API: /create

We will use save() function to create an entry/document in the DB.

First, we make sure we make the function async and we use the save() as follows. new Posts(json_obj).save(callback()) and in the callback we send the response.
a simple CRUD app using Node.js, Express & MongoDB
Add the route in PostRoutes.js file:
a simple CRUD app using Node.js, Express & MongoDB
Postman demo for /create API:
a simple CRUD app using Node.js, Express & MongoDB

ignore the “form” spelling mistake :P

Select POST in request type, paste the URL and in the Body (select JSON in data type) paste the JSON object as per our model and hit Send. Check the DB by hitting getPosts API on postman again.
a simple CRUD app using Node.js, Express & MongoDB

Get single post by id API: /getPost/:id

In this API we will use URL params to get the ID of the post and findById() to get the post from the DB.

We get the postID by using req.params.id;
a simple CRUD app using Node.js, Express & MongoDB
we query Posts collection and use findByID as follows: Posts.findById(postID, callback());
a simple CRUD app using Node.js, Express & MongoDB
Add the function in the routes file:
a simple CRUD app using Node.js, Express & MongoDB
Postman demo for /getPost/:id:
a simple CRUD app using Node.js, Express & MongoDB

Update single post with PUT: /post/:id/update

We use findByIdAndUpdate() to update a post as follows: collection.findByIdAndUpdate(id, updateData, callback());
a simple CRUD app using Node.js, Express & MongoDB
Add the function to the routes:
a simple CRUD app using Node.js, Express & MongoDB
Postman demo for /post/:id/update:
Select PUT in request type, paste the URL, get a postID from the previous response and replace “:id” with the postID and add the updated the JSON in the body and hit Send. Check the getPosts API to see the updated post.
a simple CRUD app using Node.js, Express & MongoDB

Delete single post with DELETE: /delete/:id

We use deleteOne() to delete a post as follows:collection.deleteOne(id, callback());
a simple CRUD app using Node.js, Express & MongoDB
Add the function in the routes file:
a simple CRUD app using Node.js, Express & MongoDB
Postman demo for /delete/:id request: Select DELETE in request type, paste the URL, get a postID from the previous response and replace “:id” with the postID and hit Send. Check the getPosts API to see the updated post.
a simple CRUD app using Node.js, Express & MongoDB
Pheww…, and that’s it we have created all out CURD functionalities and tested it on Postman. So for the backend folks out there, this might be enough for you to get a basic gist of Node and MongoDB. You can get more ideas methods and functionalities on the official websites of Node, Express, MongoDB and Mongoose.

The reason for this very common and simple exercise is that it will give you a good confidence boost to try more things out there.

Here is part one for this article.

If you have any queries feel free to write it on our discussion page . Also, please leave a star on our github repo if this article helped you. Thank You. :)

Copyright © 2022 Web Expe

Privacy PolicyTerms and Conditions