updating data in mongodb gives cast error

Viewed 37

code: here is the first method i tried it gives

error => CastError: Cast to ObjectId failed for value "600b0757ae00113644624036 " at path "_id"

router.post("/addnewProduct",async (req,res)=>{
    
  if(req.body._id){
    const nImage = req.files.image.name
    productSchema.findOneAndUpdate({_id:req.body._id}).then((oldp)=>{

    oldp.title = req.body.title,
    oldp.category = req.body.category,
    oldp.description = req.body.productDescription,
    oldp.price = req.body.price,
    oldp.image = nImage


    oldp.save().then((value) => {
    
    console.log("updated")

  })

})

error: error => CastError: Cast to ObjectId failed for value "600b0757ae00113644624036 " at path "_id"

second method :

 router.post("/addnewProduct",async (req,res)=>{
    
  if(req.body._id){
     productSchema.findOneAndUpdate({id:req.body._id},
      {$set: {title:req.body.title,category:req.body.category,description:req.body.productDescription,price:req.body.price,image:req.files.image.name}},
      {multi:true}
   ).then(()=>{
    res.redirect("/adminAdd/editAddProduct")
 })
1 Answers

change id to _id in findOneAndUpdate, like this

 router.post("/addnewProduct",async (req,res)=>{
    
  if(req.body._id){
     productSchema.findOneAndUpdate({_id:req.body._id},
      {$set: {title:req.body.title,category:req.body.category,description:req.body.productDescription,price:req.body.price,image:req.files.image.name}},
      {multi:true}
   ).then(()=>{
    res.redirect("/adminAdd/editAddProduct")
 })
Related