Home > Back-end >  Updating data in MongoDB overwrites the existing data
Updating data in MongoDB overwrites the existing data

Time:08-02

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"
}

CodePudding user response:

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"
}
  • Related