英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论