Home > Software engineering >  How to check duplicate value when update in NodeJS?
How to check duplicate value when update in NodeJS?

Time:08-29

i have UPDATE function in controller to update the value, but i have a problem that how can i update value that must not have a duplicate value. So, i think to do that i need to check NAME, and BRAND. Let me illustrate as below:

// update car
export async function updateCar(req, res) {
  try {
    const car = await Car.findByIdAndUpdate(req.params.car_id, req.body, {
      new: true,
    });
    if (!car) {
      return res.status(404).send();
    }
    res.status(200).send(car);
  } catch (error) {
    return res.status(500).json({
      success: false,
      message: "Server error. Please try again.",
      error: error.message,
    });
  }
}

How can i check that car NAME and BRAND must not duplicate while update. I hope anyone could help me and i very apprecaite it.

CodePudding user response:

You need to find any row with the same NAME and BRAND values without this id if an exit then no update.

 const carExit = await Car.find{
    NAME :req.body.NAME,
    BRAND :req.body.BRAND ,
    car_id: req.params.car_id,
  }
 if (!carExit) {
      return res.status(404).json({
      success: false,
      message: "duplicate value."
    });
 }

CodePudding user response:

I think this is better @Mohammad Ali Rony:

const car = await Car.find(
      req.body.name,
      req.body.brand,
      req.params.car_id,
      req.body
    );
    if (!car) {
      return res.status(404).json({
        success: false,
        message: "Duplicate value.",
      });
    }
    res.status(200).json({
      success: true,
      message: "New car updated successfully",
    });
  • Related