Node.js API + MongoDB CRUD Operations | Part 04

Nimasha Madhushani
LinkIT
Published in
7 min readJan 16, 2023

--

Artwork by Author

This is Part 04 of the series of Node.js API + MongoDB CRUD Operations. If you didn’t read Part 01, Part 02, and Part 03, you are not late…

📝Here are the links, [Part 01] [Part 02] [Part 03].

In Part 01, we initiated our application and now our server is up on port 3000. Thereafter, the database is connected successfully with the application in Part 02. Then, in Part 03, we got an idea about the model, and controllers, and retrieve the data stored in the database by using the GET HTTP method.

Super cool guys…😎

Run npm start on an integrated terminal of your application.

Let’s have a look at retiring specific data and, storing the relevant data in the database.

To insert new employees into the employees collection…,

🔷Call the method post.

🔷Call the function to handle the request.

🔷The request body should be converted to the JSON object.

📌employee.controller.js [Below post method is used to insert data]

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

📌Finally, employee.controller.js with the GET method and POST method are mentioned below.

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

const Employee = require("../models/employees.model");

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


//POST method
router.post("/", (req, res) => {
//req.body
Employee.create(req.body)
.then((data) => res.status(201).json(data))
.catch((err) => console.log(err));
});


module.exports = router;

Ooops…!🙄😵 Is this working? how can we confirm it?

Hi there, come here..and..click me, I’m Postman.

🚀The Postman platform includes a comprehensive set of tools that help accelerate the API lifecycle — from design, testing, documentation, and mocking to the sharing and discoverability of your APIs.

No worries, I’ll guide you to use this tool.

First, you have to download the postman software and install it on your machine. Then below interface will be visible to you.

  1. Click on the + icon to add a new collection
  2. Right-click on “New Collection”
  3. Click on “Add Request”
Artwork by Author

Now, a new request is in your newly created collection. So.., go through the below set of steps.

Artwork by Author

1. Rename your request as you need. Here, I renamed it Insert Employee

2. Select “POST”, because here we are to save data in the database.

3. Select the “Body” tab.

4. Click on “row”

5. Select “JSON”

✍JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications.

🔶Copy the model you created in employees.model.js

🔶Wrap the property name with double quotes and provide the corresponding details.

{
"fullName": "Raveena",
"posiotion":"Manager",
"location": "Colombo" ,
"salary":50000
}
Artwork by Author

1. Insert the correct url [path inside the use() method in index.js file and port is also can be found in same file, inside the listen() method] localhost:3000/api/employees

2. Enter data to be inserted as key value pairs [JSON].

3. Click on “Save” button.

4. Click on “Send” button, to send the request.

Now, Status:201 is displayed. Oooh.., what is that 201?🤔🤔

Status: 201For a successful request and data was created.

The POST variables are stored as key-value pairs in the body.

So, can see the return object in the postman which returns by the success call back in the post controller as below.

Artwork by Author

Even though this says the request is successful, can we believe it…😏

So…, Refresh the DB. Now go to the browser and try the way we did in Part 03. At that time you received an empty array. Now, that inserted data is inserted into the array as an object as below.

image by author

Then we can check it through the postman also by sending a GET request.

You can follow the above steps [we did in the POST request] to create a GET Request. [no need to add a request body, as we are to retrieve the data]

👻Keep it your mind to change the request type to GET .

image by author

Status: 200 OK → The request was correct and the desired response has been sent to the client.

image by author

Let’s retrieve a specific employee with the given id

Copy and paste the GET method as below.

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

💠To fetch specific data, parameter id should be included in the path get(“/:id”, .

💠And findById() method is used. Id which sends through the URL is accessed by the req parameter. findById(req.params.id)

💠If there is no id null value assigned to the data…,

❗❓Then we have to handle it…

The below condition can be used to check whether the null data is coming.

if (data) {
res.send(data);
} else {
res.status(404).json({
error: "no record with the given id",
});
}

Now, you can have this implementation.

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

Employee.findById(req.params.id)
.then((data) => {

if (data) {
res.send(data);
} else {
res.status(404).json({
error: "no record with the given id",
});
}

})
.catch((err) => console.log(err));
});

Let’s check this API using postman.

We can get an id from one data object and use it to findById. Then I copy and paste the _id of fetched data.

image by author

If we missed a character and the object _id is changed while copying and pasting, what will happen…?💥 Will try it…

Now, I changed the last digit of the object_id 4 to 3. After sending the request, our error handling part is working smoothly and returns an error message as below by mentioning,

{
"error": "no record with the given id"
}
image by author

Now, I removed the last digit “4” of the object_id.

Oops! See below to be aware of the erroneous happened here.

image by author
image by author

👁‍🗨reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer

Therefore, need to check whether the passed id is a valid object id.

So, to that import the object Id from the mongoose as below.

const ObjectId = require("mongoose").Types.ObjectId;

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

if (ObjectId.isValid(req.params.id) == false) {

res.status(400).json({
error: "given object id is not valid",
});

} else {

Employee.findById(req.params.id)
.then((data) => {
if (data) {
res.send(data);
} else {
res.status(404).json({
error: "no record with the given id" + req.params.id,
});
}
})
.catch((err) => console.log(err));

}
});

Now, BSONTypeError won’t be received when the object_id type is changed, because we have handle it by checking whether the passing object_id is a valid one or not as below,

image by author

Status: 400 Bad Request → Indicates that the server cannot or will not process the request due to something that is perceived to be a client error.

Even though the object_id tye is valid, if there is no object_id which is found, the below error handling part will be worked.

image by author

Status: 404 Not Found → Response that indicates that the server won’t process the request because it is unable to locate the resource specified in the request.

So…, finally, our controller can POST data, GET all data in the DB and GET specific data in the DB. For that whole completed employees.controller.js file is as below.

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

const ObjectId = require("mongoose").Types.ObjectId;

const Employee = require("../models/employees.model");

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

//POST method
router.post("/", (req, res) => {
//req.body
Employee.create(req.body)
.then((data) => res.status(201).json(data))
.catch((err) => console.log(err));
});

//GET method [get specific data]
router.get("/:id", (req, res) => {
if (ObjectId.isValid(req.params.id) == false) {
res.status(400).json({
error: "given object id is not valid",
});
} else {
Employee.findById(req.params.id)
.then((data) => {
if (data) {
res.send(data);
} else {
res.status(404).json({
error: "no record with the given id" + req.params.id,
});
}
})
.catch((err) => console.log(err));
}
});

module.exports = router;

🎃 Source Code: https://github.com/Nimasha-Madhushani/NodeJS-Rest-API

I think we need a break and it is better to continue with Part 05. 😋 So, practice these things. If you have anything to clarify, please drop a comment under this post or send a private note.

Thank you all my guys for staying with me 💖💖

Until then Bye for All 👋👋👋

--

--