【问题标题】:Type '(err: any) => void' has no properties in common with type 'QueryOptions' on Node route类型 \'(err: any) => void\' 与节点路由上的类型 \'QueryOptions\' 没有共同的属性
【发布时间】:2023-01-11 04:47:23
【问题描述】:

我在 Node 控制器中有以下路由,它给我一个阻止 Node 运行的错误

public async deletePost(req: Request, res: Response) {
    const { id } = req.params;
    const deletedPost = await BlogPostModel.findByIdAndDelete(id, err => {
      if (err) {
        res.status(400).send.send('Error deleting post');
      }
    });

    // needs to send error if post not found (400 status code)

    res.status(200).send(deletedPost);
  }

我的代码的 err => { 部分出现错误:

Type '(err: any) => void' has no properties in common with type 'QueryOptions'

我不完全理解这个错误,但听起来它要求我在错误处理回调函数中输入参数。但是,我也试过(err:any)=>,但效果不佳。谁能在这里告诉我如何正确使用回调函数进行错误处理?

【问题讨论】:

    标签: node.js typescript express mongoose


    【解决方案1】:

    似乎第二个参数必须是 QueryOptions 类型,但你传递了一个函数

    这不是你应该如何处理错误,你不能混合承诺和回调

    public async deletePost(req: Request, res: Response) {
      const { id } = req.params;
      try {
        const deletedPost = await BlogPostModel.findByIdAndDelete(id);
      } catch (err) {
        return res.status(400).send.send("Error deleting post");
      }
    
      res.status(200).send(deletedPost);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-27
      • 2019-03-27
      • 2023-01-05
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      相关资源
      最近更新 更多