M
Mayur Nalwala
Aug 05, 2022
CRUD app using Node.JS, Express & MongoDB - Part 2

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.

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.jsconst 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.jsconst express = require('express');const app = express();// create a base route with a responseapp.get('/', (req,res) => {res.send('server running');})app.get('/getPosts', (req, res) => {const posts = await Posts.find();res.json(posts);})module.exports = app
// server.jsconst mongoose = require('mongoose');require('dotenv').config({ path: '.env' });// Database connectionmongoose.connect(process.env.DATABASE,{useUnifiedTopology: true,useNewUrlParser: true});mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promisesmongoose.connection.on('error', (err) => {console.error('Database Connection Error');});// require our models here so that it can be accessed throughtout the applicationrequire('./Models/Posts');// require app.jsconst app = require('./app');// start the server on port 3000const 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).





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 .

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.



ignore the “form” spelling mistake :P

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;




Update single post with PUT: /post/:id/update
We use findByIdAndUpdate() to update a post as follows: collection.findByIdAndUpdate(id, updateData, callback());

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.

Delete single post with DELETE: /delete/:id
We use deleteOne() to delete a post as follows:collection.deleteOne(id, callback());


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. :)