使用Knex检查现有id



我正在使用express和Knex做CRUD路由。对于更新和删除路由,我可以选择id,但如果id不存在,我就会遇到问题。如果id不存在,我需要显示错误消息和状态码400。是否有问题,我的代码没有达到捕获显示错误?我需要一个不在数据库中的id的条件吗?

我累了为有条件的if id添加if语句。长度=== 0,但我仍然得到状态200时,我测试或id不在数据库中。我使用邮差来测试错误,如果我使用id不在数据库中。

//PUT update todo
router.put('/:id', (req, res) => {
knex('todos')
.where({
id: req.params.id   
})
.update(req.body)
.returning('*')
.then(todos => {
res.status(201).json(todos[0]) 
})
.catch(error => {
res.status(400).send(error)

});
})
//DELETE 
router.delete('/:id', (req, res) => {
knex('todos')
.where({
id: req.params.id
})
.del()
.then(function() {

knex.select() //select all *
.from('todos')
.then(function(todos){
res.status(200)
res.send(todos);
})

})
.catch(error => {
// console.log(error.message)

res.status(400).send(error.message)
})
})

Knex不会抛出错误,如果没有行被更新或删除,所以你的catch块不会触发。

当你调用returning函数时,它们应该返回一个对象数组,表示更新/删除的内容,这样你就可以检查它是否为空,即

router.put('/:id', (req, res) => {
knex('todos')
.where({
id: req.params.id   
})
.update(req.body)
.returning('*')
.then(todos => {
if (todos.length) {
res.status(201).json(todos[0]) 
} else {
res.status(400).send(error)
}
})
.catch(error => {
res.status(400).send(error)
});
})

最新更新