我有个密码:
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年,我认为我应该继续使用异步/等待语法,我这样做了:
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,有人知道为什么吗?
发布于 2019-03-30 15:09:41
你在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 });
}
});https://stackoverflow.com/questions/55432737
复制相似问题