【问题标题】:updating data in mongodb gives cast error更新 mongodb 中的数据会导致转换错误
【发布时间】:2021-01-23 15:12:58
【问题描述】:

代码:这是我尝试的第一种方法

error => CastError: Cast to ObjectId failed for value 路径“_id”处的“600b0757ae00113644624036”

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 路径“_id”处的“600b0757ae00113644624036”

第二种方法:

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

【问题讨论】:

    标签: javascript node.js backend


    【解决方案1】:

    在findOneAndUpdate中把id改成_id,像这样

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

    【讨论】:

      猜你喜欢
      • 2013-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      相关资源
      最近更新 更多