‘QueryOptions’ 上的类型 ‘(err: any) => void’ 与 Node 路由上没有共同属性。

huangapple go评论76阅读模式
英文:

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

问题

以下是您要翻译的部分:

我在一个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('删除帖子时出错');
      }
    });

    // 需要在未找到帖子时发送错误(400状态码)

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

我的代码中的`err => {`部分出现错误,错误信息如下:

Type '(err: any) => void'与类型'QueryOptions'没有共同的属性

我不完全理解这个错误,但听起来它要求我在错误处理回调函数中为参数指定类型。然而,我也尝试过`(err:any)=>`,但这也不起作用。是否有人能告诉我如何在这里正确使用回调函数进行错误处理?
英文:

I have the following route in a Node controller that is giving me an error that prevents Node from running

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

I get an error for the err => { section of my code saying:

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

I don't fully understand this error, but it sounds like its requiring I type out the argument in the error handling callback function. However, I've also tried (err:any)=> and that doesn't work as well. Would anyone be able to fill me in on how to correctly use a callback function for error handling here?

答案1

得分: 2

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

这不是处理错误的正确方式,您不能混合使用 promises 和回调函数。

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("删除文章出错");
  }

  res.status(200).send(deletedPost);
}
英文:

Seems like the second argument must be of type QueryOptions, but you pass a function instead

It's not how you should handle errors, you can't mix promises and callbacks

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

huangapple
  • 本文由 发表于 2023年1月11日 04:41:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75075610.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定