I am doing CRUD routes using express and Knex. For the update and delete routes, I can select the id but I am having an issue with if the id does not exist. If the id does not exist I need to show the error message and status code 400. Is there an issue with my code not reaching the catch to display the error? Do I need a conditional for ids not in the database?
I tired adding a if statement for the conditional if the id.length === 0 but I was still getting status 200 when I tested or an id that was not in the database. I am using Postman to test for the error if I use an id not in the database.
//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)
})
})