【问题标题】:how check if doc was updated using updateOne() [mongoose,React , Node js, Mongodb]如何使用 updateOne() 检查文档是否已更新 [mongoose,React,Node js, Mongodb]
【发布时间】:2021-01-24 01:11:09
【问题描述】:

这是我的更新代码,显然这有效,但我不知道如何以编程方式检查它是否有效,我有一个想法,即在更新之前将要更新的字段存储在 temp 变量中,然后将其与 updatedDoc 进行比较但是t 看起来很奇怪,我想知道是否有更简单的方法

router.post('/update',async(req,res)=>{
    const {id,addresses}=  req.body
    try {      
        const targetDoc=await UserModel.findOne({_id:id});

        const updates = { addresses};
        const updateResponse = await targetDoc.updateOne(updates);
        // need to check for succes here 


        const updatedDoc = await UserModel.findOne({_id:id});
        res.sendStatus(200)


    } catch (error) {
       console.log(error)
    }
})

【问题讨论】:

标签: node.js reactjs mongodb mongoose


【解决方案1】:

检查文档是否可以更新的最佳方法是检查更新之前。这样,如果您在更新之前所做的任何断言都通过了,那么您将知道它已成功更新:

router.post('/update',async(req,res)=>{
  try { 
    // move this statement inside the try block; otherwise if "id" or "addresses"
    // is missing from req.body, it'll throw an unhandled destructure error
    const { id, addresses} = req.body;
    
    // make sure the id is present
    if (!id) throw String("Invalid request. You must supply a user id to update!");
    
    /* 
      I'm not sure how "addresses" is structured, but if you expect
      it to be an object, then make assertions against an object with structure:
      if(!object || object.length <= 0 || !object.name || !object.city ...etc)

      if it's an array, then make assertions that it's not empty...
    */
    if (addresses assertions are invalid)
      throw String("Invalid request. The addresses you've provided are not valid! Please try again.");       

    /* 
      If the above passes the req.body assertions, then the only thing  
      that can fail here is if "id" is invalid. If it's invalid, then Mongoose
      will throw an error if "updateOne" doesn't find the document; 
      otherwise, you'll know the document has been successfully updated.    

      Optionally, you can manually handle "id" errors by finding and throwing
      an error if the document is empty BEFORE attempting to update, 
      for example...

      const existingUser = await UserModel.findOne({ _id: id });
      if (!existingUser) throw String("Unable to locate that user to update.");

      await existingUser.update(addresses);
      await existingUser.save();
    */
    await UserModel.updateOne({ _id: id }, { addresses });

    // if the above is successful, then the client should receive this
    // message:
    res.status(200).send("Successfully updated user!");
  } catch (error) {
    // if any of the above assertions are unsuccessful, then the 
    // client should receive an error message:
    res.status(400).send(error.toString());
  }
});

附带说明,始终返回响应!即使只是res.end()。如果不这样做,将导致请求挂起/未处理的承诺。

【讨论】:

  • 感谢您的明确回答,我现在可以投票了,因为我还没有这个特权,但当我可以时肯定会的
  • 关于断言,在客户端,我确保除非地址对象有效,否则不会发送任何 api 调用
  • 很容易绕过客户端,直接向API发送请求。在客户端和 API 上进行断言。
猜你喜欢
  • 2017-01-06
  • 2016-08-01
  • 1970-01-01
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
  • 2017-09-22
  • 1970-01-01
相关资源
最近更新 更多