0

Getting this error on trying to update....mongoose is throwing this error on using the code below....have tried using const project = {...} instead of new Product({...}) but no luck.

router.put("/:id", multer({storage: storage}).single("image") , (req, res, next) => {
    let imagePath = req.body.imagePath;
    if (req.file) {
        const url = req.protocol + "://" + req.get("host");
        imagePath = url + "/images/" + req.file.filename
    }
    const product = new Product(
        {
            _id: req.body.id,
            title: req.body.title,
            cost: req.body.cost,
            description: req.body.description,
            imagePath: imagePath
    
        }
    ) ;
    console.log(product)
    Product.updateOne({_id: req.params.id}, product)
    .then(result => {
        console.log(result);
        res.status(200).json({ message: "Update Successful !!"});
    });
});
Alish Madhukar
  • 391
  • 1
  • 5
  • 18

1 Answers1

2

You need to remove the key _id from the object that is being used for updating the document.

const product = new Product(
    {
        title: req.body.title,
        cost: req.body.cost,
        description: req.body.description,
        imagePath: imagePath
    }
) ;

This will solve your problem.

Thing is, while doing an update on the document whose _id matches with the one you passed in your code,

    Product.updateOne({_id: req.params.id}, product)

you are trying to update the value of _id field as well. _id by default is immutable which means it can not be updated, as it represents the uniqueness of the document.

Edit: If you need to update the _id of the document as well, then you can take a reference from here to do this. Though the _id can not be updated directly, but there is a workaround for doing that.

How to update the _id of one MongoDB Document?

Avani Khabiya
  • 1,207
  • 2
  • 15
  • 34