Finding an id's presence with Knex

Currently, I am working on setting up CRUD routes using Express and Knex. When it comes to the update and delete routes, I have encountered an issue regarding handling cases where the provided ID does not exist in the database. In such situations, I need to display an error message along with a status code of 400. I suspect that there might be an issue in my code preventing it from reaching the catch block to handle this error scenario. Could it be necessary to implement a condition to check for IDs that are not present in the database?

I attempted to address this by adding an if statement to check if the length of the ID is equal to 0, but unfortunately, when testing with Postman using an ID that is not in the database, I was still receiving a status code of 200 instead of 400. Here is the snippet of code I am currently working with in my Express routes:

//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)
    })
})

Answer №1

Knex does not generate an error if no rows are updated or deleted, so the catch block will not be triggered.

However, since you are using the returning function, it should return an array of objects representing the updated/deleted data. You can check if this array is empty to determine if the operation was successful, for example:

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)
    });
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it important to maintain the scroll to top button at a consistent height?

I am facing an issue with my button. I want the button to remain at a consistent height even when the window size is adjusted vertically. How can I ensure that the button does not move or get pushed down as the height changes? http://jsfiddle.net/ccq9cs9L ...

Start the embedded YouTube live stream on autoplay

When it comes to autoplaying a regular YouTube video, there are various solutions available. However, these methods do not always work for livestreams. I attempted to automatically click the embedded link using the following code: <script> var els = ...

Creating an asynchronous function in Node.js that returns a promise, but experiencing unexpected behavior when using console.log to display the result

Recently, I created a simple and compact API that determines the gender of a person. It functions by sending a get-request to a specific page which responds with a JSON object. This snippet illustrates how my module works: 'use strict'; const ht ...

Tips for adding/removing items in arrays using Ember.js

Is it possible to modify an array within an Ember object using methods like push and pop while still keeping the UI bindings updated? While I can easily display the contents of an array in an Ember object using Handlebars, making changes directly to the ...

The attention remains fixed at the top of the page

I have implemented an update panel along with pagination links using a repeater control at the bottom of my page. However, I am encountering an issue where clicking on the pagination links does not bring the page to the top. I attempted to use the followin ...

Custom attribute in ReactJS component - I am not defined in my custom attribute in React component

I am currently working with ReactJS and I am facing an issue regarding accessing a custom attribute -name- of my ReactJS component. Despite trying to use e.target.name, it keeps returning "undefined" on my console. I cannot seem to figure out why this is ...

Choosing a specific column in an HTML table using jQuery based on the text within it

I have a table with a similar structure as shown below: <table> <c:forEach ...> <tr> <td>test</td> // this is the initial value <td>random value</td> <td>random value</td&g ...

The StereoEffect is unable to render the texture from the WebGLRenderTarget

I am looking to blur a panoramic view to create a user-interface in front of the blurred view. To achieve this, I am using a fragment-shader-based implementation to compute the blurred image on the client side. Everything works perfectly when using the re ...

I am retrieving data from a service and passing it to a component using Angular and receiving '[object Object]'

Searching for assistance with the problem below regarding my model class. I've attempted various approaches using the .pipe.map() and importing {map} from rxjs/operators, but still encountering the error message [object Object] export class AppProfile ...

"Troubleshooting: Node.js encountering a path error while loading a JSON file with

I am organizing a collection of folders and files structured like this: viz |_ app.js // node application |_ public |_ css |_ bubblemap.css |_ images |_ nuts |_ nuts0.json |_ script ...

Is there a way for me to view the output of my TypeScript code in an HTML document?

This is my HTML *all the code has been modified <div class="testCenter"> <h1>{{changed()}}</h1> </div> This is my .ts code I am unsure about the functionality of the changed() function import { Component, OnInit } f ...

Various Issues Regarding Jquery Libraries

Here's a question on my mind... Currently, in my main file index.php, I have imported jquery 2.0.3 like this: <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> The issue arises bec ...

Obtain the complete model within Backbone JS

When working with backbone javascript models, we can obtain individual items like this: var type = this.model.get("type"); The "type" variable is typically defined on the server side and then accessed in JavaScript using the above syntax. But is it poss ...

Children can easily access multiple items within a list by using the ul tag

I am struggling with changing the class of ul inside the ul.navigator. I want to change it only when I click on a particular li, but my current approach doesn't seem to be working. Can anyone provide some guidance or assistance? $('.navigator& ...

How to access the body element from within an AngularJS directive

Is there a way to access the body element in an angular directive without using jQuery? I want to achieve something similar to $('body').innerWidth(); but using Angular's built-in jqlite implementation instead of jQuery. ...

Middleware in Express.js that allows a function to be executed every time `res.send()` is called

As of now, I am creating APIs using express.js and I aim to send a standard response format like so : res.send({status : 'suceess' , msg : '' , data : [] }); Across all the controllers (functions managing my routes) My attempted sol ...

The File is not being successfully sent to the controller in MVC due to AJAX returning an undefined value

I recently created an AJAXUpload method within a cshtml file in my C# MVC project: function AjaxUpload(url, method, data, successFunction, errorFunction, skipErrorDlg) { $.ajax({ contentType: false, processData: false, url: url ...

The request for a base64 image in nodejs has been denied due to the entity being too

I have a JSON data with the base64 of an image that I am trying to send {desc: "hi", img: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABMY" } However, I encountered this error PayloadTooLargeError: request entity too large at rea ...

Looking to create a loop that continues as long as a JSON dataset remains assigned to a specific variable

I've been trying to retrieve JSON data, but I seem to have hit a snag. I'm not sure where I went wrong or how to correct it. [ { "userId": 1, "title": "A", "body": "B" }, { "userId": 1, "title": "C", "body": "D" }, { "userId": 2, "title": "E", " ...

Loading Textures in Three.js Using async / await is the Way to Go

Recently, I took a Drawing class and learned about creating objects: export class Drawing { constructor(texture) { const material = new MeshBasicMaterial({ color: 0xffffff, map: texture }); this.m ...