UPDATE USER INFORMATION IN NODEJS

 

In the previous blog post, we covered essential functionalities such as user registration and login with our Nodejs Application. As we continue to explore the key aspects of CRUD operations (Create, Retrieve, Update and Delete), we have successfully implemented the first two operations. Now, in this blog, we will focus on the process of updating registered user information within the application.

Let’s delve into the details of how we can efficiently handle user data updates and ensure a smooth user experience while maintaining the integrity of our application’s data.

How to Update User Information in our Nodejs Application??

When it comes to updating user information, it’s crucial to have a unique or primary key that allows us to identify and modify the details of a specific user. In our application, we’ve incorporated a unique key, which we discussed in detail in our previous blog on “User Model Creation”. Specifically, we declared the “emailId” field as the unique identifier for each user.

To initiate the update process, we leverage this “emailId”, field as a reference and proceed to modify the relevant user fields stored in the user collection. In Nodejs, the update statement involves two key arguments:

  • The unique field of the user information, in this case, the “emailId”.
  • The new values of the fields that need to be updated.

Utilizing this approach ensures that we can seamlessly update user information while maintaining the integrity and uniqueness of each user’s data within our application. Let’s now dive deeper into the update process to enhance our understanding.

Implementation of Update Operation

In this blog, we will utilize the userController and userRoutes classes introduced in our previous blog post (click here) to implement the update functionality.

userController:- we follow the below steps to update the user information in the code.

  • First, we check if the user exists in the Nodejs application based on their “emailId”.
  • If the user is found, we proceed to update the required user information and return a success message confirming that the user data has been updated.
  • However, if the user is not found, we handle this situation by returning an error message stating, “User doesn’t exist in the application
// Writing a method to update the user information
exports.updateUser = async (req, res) => {
  try {
    // checking whether the user exists in the Nodejs Application
    // with the help of the emailId
    let existingUser = await userRepo.find({ emailId: req.body.emailId });

    // if the existingUser length greater than 0
    // i.e., the user exists in the application
    if (existingUser.length > 0) {
      // Now we can update the info of the user based on his emailId
      // Here we are updating the information of name, mobile and DOB
      let updateUserInfo = await userRepo.updateOne(
        { emailId: req.body.emailId },
        {
          $set: {
            name: req.body.name,
            mobile: req.body.mobile,
            dateOfBirth: req.body.dateOfBirth,
          },
        }
      );

      res.status(200).json({
        status: "success",
        message:
          "User Information Updated Successfully for userName: " +
          existingUser[0].userName,
      });
    } else {
      // if the existingUser length is not greater than 0
      // i.e., the user doesn't exists in the application

      res.status(400).json({
        status: "failed",
        message: "User doesn't exist in the Application",
      });
    }
  } catch (err) {
    res.status(400).json({
      status: "failed",
      message: err.message,
    });
  }
};


userRoutes :-  In this class, we create an api to perform routing on the update method.

// api call to update the user
router.put('/updateuser', userController.updateUser);


Let’s see how the data is updated, comparing with previous data stored in the user collection.

Previous Data:- 

Now we will update some of the user information, by hitting the update API from postman


We can refresh the users collection in the mongoDb to see the updated as below:-


Happy Coding !!

Harsha Vardhan Garlapati

As a software engineer and technology enthusiast, I thrive on exploring the ever-evolving world of technology and leveraging it to create innovative solutions. With a passion for sharing knowledge and insights, I also delve into the world of blogging to inspire and educate others in the realm of software development. Beyond the realm of code, I find joy in exploring new destinations as a passionate traveler, embracing diverse cultures, and broadening my horizons. In my free time, I cherish moments spent with friends, valuing the connections and experiences that enrich my life. Combining my technical expertise, love for writing, adventurous spirit, and the importance of human connections, I aim to leave a positive impact on the world through my work, experiences, and interactions. Let’s embark on this exciting journey together, exploring the wonders of technology while cherishing the moments that truly matter.

Post a Comment

Previous Post Next Post