Updating data in MongoDB overwrites the existing data

Issue

I want to set up the user profile after verifying the phone number by providing their details like firstname, lastname, email etc.

exports.profileSetup = async (req, res) => {
  try {
    const { firstName, lastName, email, country, state, zipcode, userId } =
      req.body;
    const User = await Auth.findOne({ _id: userId });
    if (!User) {
      return res.json({ message: "No user found" });
    }

    User.firstName = firstName;
    User.lastName = lastName;
    User.email = email;

    if (User.email) {
      otp = otpGenerator(4);
      emailOtp({ email: req.body.email, otp });
      User.otp = otp;
    }

    const save = await User.save();

    return res.status(200).json({
      success: true,
      msg: "You are now all set",
      data: { User: save },
    });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
};

When I pass the following request from the postman then it gets saved and generates OTP as well. No problem whatsoever.

{
    "userId":"62e7bd9ae6d785a44db9d8f5",
    "email":"[email protected]",
    "firstName":"ThingSome"
}

But when I send the below request then it removes email from the database and saves only firstname.

{
    "userId":"62e7bd9ae6d785a44db9d8f5",
    "firstName":"Something"
}

Solution

That’s because you update the records with a new object and the object you send contain null value for the email field

I’m not sure if you can update just specific values, but you can run a SELECT first and get the current values. Then you can use those values to keep what you want to keep:

const User = await Auth.findOne({ _id: userId });
{
    "userId":"62e7bd9ae6d785a44db9d8f5",
    "email": User.email,
    "firstName":"Something"
}

Answered By – Alexandru DuDu

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published