Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当我使用DELETE方法时,即使id不存在,我还是成功地得到了JSON响应_Javascript_Node.js_Postman - Fatal编程技术网

Javascript 当我使用DELETE方法时,即使id不存在,我还是成功地得到了JSON响应

Javascript 当我使用DELETE方法时,即使id不存在,我还是成功地得到了JSON响应,javascript,node.js,postman,Javascript,Node.js,Postman,我想按其id删除项目,但即使id不存在,我也得到了成功的响应 exports.deleteItemById = (req, res, next) => { Item.findByIdAndDelete(req.params.id, (error, item) => { if(error){ return res.status(201).json({ success: false,

我想按其id删除项目,但即使id不存在,我也得到了成功的响应

exports.deleteItemById = (req, res, next) => {

       Item.findByIdAndDelete(req.params.id, (error, item) => {
        if(error){
           return res.status(201).json({
                success: false,
                message: "Item could not be found"
            })
        }
        res.status(200).json({
          success: true
        });
      }); 
    };
比如说,, 如果我使用以下项目ID:5d540f7c69a372ddc13dc77f使用Postman删除其中一个项目,它会工作并删除该项目,并显示“success:true”作为JSON响应,但在下一次尝试中,如果我使用相同的ID,我仍然会得到“success:true”,这不是我想要的结果。如果ID已不存在,我希望收到“找不到项目”消息。

请说:

  • findbyianddelete
    findOneAndDelete
  • findOneAndDelete
    “查找匹配的文档,将其删除,并将找到的文档(如果有)传递给回调。”
  • 因此,只需检查是否返回了文档(
    ):

    exports.deleteItemById = (req, res, next) => {
    
           Item.findByIdAndDelete(req.params.id, (error, item) => {
            if(!item){
               return res.status(201).json({
                    success: false,
                    message: "Item could not be found"
                })
            }
            res.status(200).json({
              success: true
            });
          }); 
        };
    

    是,这不会给出错误,因为在mongoDB中,如果找不到文档,它将返回
    {“nRemoved”:0}
    。如果要检查项目是否存在,则必须检查已删除的文档。请参考以下代码

    exports.deleteItemById = (req, res, next) => {
    
       Item.findByIdAndDelete(req.params.id, (error, item) => {
        if(!item){ // this will be null if no document with the mentioned id existed
           return res.status(201).json({
                success: false,
                message: "Item could not be found"
            })
        }
        res.status(200).json({
          success: true
        });
      }); 
    };
    

    你能分享你的findByIdAndDelete方法吗?你使用的是什么框架?@adrenalin我使用的是Express框架。@LordOfSun我没有写findByIdAndDelete。这是猫鼬提供的功能。以下是链接:请不要使用2xx状态代码来表示故障。如果删除失败,代码将返回http状态代码201(已创建)。如果要传达错误,应根据实际错误使用4xx或5xx状态代码。这样一来,api的使用就变得非常简单,因为您不必阅读响应正文!谢谢,谢谢你的回答!这就是我要找的。