Search code examples
node.jstypescriptexpressmongoose

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


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?


Solution

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