Node.js API + MongoDB CRUD Operations | Part 03

Nimasha Madhushani
LinkIT
Published in
4 min readJan 6, 2023
Artwork by Author

This is Part 03 of the series of Node.js API + MongoDB CRUD Operations. If you didn’t read Part 01 and Part 02, you are not late here are the links, and spent little time on them. [Link to Part 01] [Link to Part 02].

We have initiated our application and now our server is running on port 3000 in Part 01. Furthermore, we have connected the database successfully in Part 02.

Run the application in an integrated terminal by using npm start. Now, the time is to implement the model and controllers.

📌What is a model?

The model you define in the NodeJS server is an abstraction of the data in your MongoDB database, which is represented as a document. Because of this abstraction, you may use the “Mongoose” schemas to construct a blueprint of how you want the added data to look and behave. Then simply, models are data structures that we use to define the shape of our data.

Now should create a corresponding model class. Then, create a new folder for models and create a new file inside it as employees.model.js .

After that, import the mongoose package inside employees.model.js in order to create the model. Then, call the method called model() .

In the first parameter, we can name the model and in the second parameter, we can pass the schema which is the structure of the data that we are going to save to the DB. Then as the third parameter, we should enter the name that we want to name the collection.

const mongoose = require("mongoose");

mongoose.model(
"Employee",
{
fullName: { type: String },
posiotion: { type: String },
location: { type: String },
salary: { type: Number },
},
"employees"
);

As the last step, we need to export the model as below. Now we have completed the model.

const mongoose = require("mongoose");

module.exports=mongoose.model(
"Employee",
{
fullName: { type: String },
posiotion: { type: String },
location: { type: String },
salary: { type: Number },
},
"employees"
);

📌What is a controller in this application?

Controllers are JavaScript files that contain a set of methods, called actions, reached by the client according to the requested route. The controller code acts as a liaison between the Model and the View, receiving user input and deciding what to do with it. It’s the brains of the application, and ties together the model and the view. The controller accepts user requests, interacts with the model, and selects the view for the response.

Let's create the employee controller. For that create a new folder called controllers. Then create the employee.controller.js file inside the controller folder. Now we have to import express to get used to HTTP methods. Thereafter, the Router object should be created as below,

const express = require("express");
const router = express.Router()

The Express router object is a collection of middlewares and routes. It is a mini-app within the main app. It can only perform middleware and routing functions and can’t stand on its own. It also behaves like middleware itself, so we can use it with the app.

📌What is HTTP Get Method?

The GET method is used to retrieve information from the given server using a given URI.

Now, the time is to implement the get method. router.get( path, callback ) Here, the path is ‘/’ and callback is (req,res)=>{ } .

⭕Parameters:

  1. path: It is the path for which the middleware function is being called.
  2. callback: They can be a middleware function or a series/array of middleware functions.
router.get('/',(req,res)=>{

})

Now, your employee.controller.js file is as below.

const express = require("express");
const router = express.Router();

router.get("/", (req, res) => {

});

Then we need to import the model that we implemented as below in employee.controller.js file.

const Employee=require('../controllers/employee.model')

So, the model exported from employees.model.jsis imported. Here, the character convention of the variable normally should be started with uppercase.

Now, call the method find() inside the callback function. Then we can write the success response.

router.get("./", (req, res) => {
Employee.find()
.then((data) => res.send(data))
.catch((err) => console.log(err));
});

Here this get method is used to retrieve all the data from the employee collection. To do that, we need to export the router object here.

const express = require("express");
const router = express.Router();

const Employee = require("../models/employee.model");
router.get("/", (req, res) => {
Employee.find()
.then((data) => res.send(data))
.catch((err) => console.log(err));
});
module.exports=router

And import the exported router object above inside the index.js file(server).

const employeeRoutes=require('./controllers/employee.controller')

Now we can configure the routing for the application by calling app.use() method inside the index.js file. Then need to provide the base path and then pass the employeesRoute .

app.use('./api/employees',employeeRoutes)

Finally, your index.js file is as below.

const express = require("express");
const bodyParser = require("body-parser");
const dbConnection = require("./db.js");
const employeeRoutes=require('./controllers/employee.controller')
const app = express();

//middleware
app.use(bodyParser.json());

app.use('/api/employees',employeeRoutes)

dbConnection()
.then(() => {
console.log("DB is connected!!")
app.listen(3000, () => console.log("Server is started on 3000"));
})
.catch((err) => console.log(err));

Here we have hosted the server on port 3000. Then in the browser, we can check the get request as below. To that, you can use the URL localhost:3000/api/employees. So, we can see the empty array since we didn’t insert data into the database.

image by author

Wow…, brilliant…😍 we have come to a certain level. I think having a small break is better. Ok then will meet with Part 04 to continue this. There we are to discuss other HTTP methods and some software like postman.

If you need any clarification, please drop a comment here.

Thank you for reading this article, bye for now guys…👋👋👋👋👋

--

--