javascript - Express Router delete with mongoose 不适用于 ES8 语法
问题描述
我有这个代码:
router.delete('/:id', (req, res) => {
Input.findById(req.params.id)
.then(Input => Input.remove().then(() => res.json({ success: true })))
.catch(err => res.status(404).json({ success: false }));
});
因为我们在 2019 年,我想我应该继续使用 async/await 语法,我这样做了:
router.delete('/:id', async ({ params }, res) => {
try {
const Input = await Input.findById(params.id);
await Input.remove();
res.json({ success: true });
} catch (error) {
res.status(404).json({ success: false });
}
});
ID按预期接收,但由于某种原因input.findById返回null,有人知道为什么吗?
解决方案
您正在Input
与const Input
之前的findById
. 为它使用不同的名称(即使只是小写也足够了;请记住,最初加盖的标识符主要用于构造函数,而不是非构造函数对象):
router.delete('/:id', async ({ params }, res) => {
try {
const input = await Input.findById(params.id);
// ^-------------------------------------------- here
await input.remove();
// ^-------------------------------------------- and here
res.json({ success: true });
} catch (error) {
res.status(404).json({ success: false });
}
});
如果你喜欢,顺便说一句,你可以做嵌套解构来挑选id
:
router.delete('/:id', async ({params: {id}}, res) => {
// ^^^^^^^^^^^^^^======================
try {
const input = await Input.findById(id);
// ^=========================
await input.remove();
res.json({ success: true });
} catch (error) {
res.status(404).json({ success: false });
}
});
推荐阅读
- ruby-on-rails - 使用 mail_form freeze 发送电子邮件,没有错误 rails
- r - 在函数内,如果找不到 xpath,则返回 NA 或 0
- python - 如何在普通图像上粘贴半透明图像并获得透明度 PIL?
- composer-php - 在 laravel 8 中安装氩仪表板时找不到类“Laravel\Ui\UiCommand”
- windows-10 - Windows 10 搜索不包括带点名称的文件夹?
- c++ - 从可执行文件中删除调试“标志”的 C++ 方法
- html - 引导轮播不工作或滑动
- reactjs - 如何在 ReactHooks 中使用 useRef 使子菜单的每一项都会独立改变背景
- react-native - 在反应本机导航中自定义标题
- gpu - 使用 nvidia gpu 使用 xserver (mobaxterm) 在 wsl2 中运行gazebo7(错误:[gazebo-4] 进程已死亡)