Adding, applying, and removing operations do not generate errors

I'm facing an issue while working on a REST API using JS. The code is functioning fine, but I encounter a problem when trying to delete, put, or patch an entry that doesn't exist. Instead of returning an error, it displays a success message. The GET route, however, works perfectly.

app.route("/verbrauch/:parameterVariable")

    .get((req, res) => {
        Verbrauch.findOne({
            bezeichnung: req.params.parameterVariable
        }, (err, foundEntries) => {
            if (foundEntries) {
                res.send(foundEntries);
            } else {
                res.send("Success");
            }
        });
    })


    .put((req, res) => {
        Verbrauch.update({
                bezeichnung: req.params.parameterVariable
            }, {
                bezeichnung: req.body.bezeichnung,
                stueckzahl: req.body.stueckzahl,
                monat: req.body.monat,
                jahr: req.body.jahr,
            }, {
                overwrite: true
            },
            err => {
                if (!err) {
                    res.send("Success");
                } else {
                    res.send(err);
                }
            }
        );
    })


    .patch((req, res) => {
        Verbrauch.update({
                bezeichnung: req.params.parameterVariable
            }, {
                $set: req.body
            },
            err => {
                if (!err) {
                    res.send("Success")
                } else {
                    res.send(err);
                }
            }
        );
    })

    .delete((req, res) => {
        Verbrauch.deleteOne({
                bezeichnung: req.params.parameterVariable
            },
            err => {
                if (!err) {
                    res.send("Success");
                } else {
                    res.send(err);
                }
            }
        );
    });

Answer №1

There are several factors contributing to this issue.

First off, if you attempt to update something that does not exist in the database, instead of returning an error, it will simply return a null value in the result.

Additionally, it is not advisable to use res.send(err) in your code. By doing so, ExpressJs will automatically assign a default status code of 200, indicating success. To handle errors properly, consider using:

res.status(400).send(err)

or

res.status(500).send(err)

Answer №2

To implement an update method using a callback function with 2 parameters (error, writeOpResult), consider the following solution:

app.put((req, res) => {
    Verbrauch.update({
            bezeichnung: req.params.parameterVariable
        }, {
            bezeichnung: req.body.bezeichnung,
            stueckzahl: req.body.stueckzahl,
            monat: req.body.monat,
            jahr: req.body.jahr,
        }, {
            overwrite: true
        },
        (err,res) => {
            if (!err) {
                res.send("Success");
            } else {
                res.status(404).send(err);
            }
        }
    );
})

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

Confirmation dialog with user-defined button text

When the confirm prompt box is used, it typically displays "ok" and "cancel" buttons. I am looking to customize the label text for the buttons to read as Agree and Not Agree instead. If you have any suggestions on how to achieve this modification, please ...

Extracting data from an API response with rest Assured: A simple guide

I am new to utilizing Rest Assured for API testing. My response JSON contains nested arrays with details of spends on various merchants, and I specifically need to extract the spend value for Netflix. How can I create a condition to retrieve the absolute v ...

Building on the Vuejs3 and Vuex4 framework, create a conditional rendering feature that triggers upon

I have a unique setup where custom objects are used to hold child objects full of data. The child objects start with null values for all properties, allowing them to be filled with data from remote sources when referenced. This results in a lazy-loading sy ...

MongoDB failing to retrieve updated data

I have set up MongoDB Atlas to host my MongoDB database. The backend of my application is written in Node.js and I am using Mongoose for interacting with the database. All the documents in my collection share the same properties. To test a new feature, I ...

Is it possible to operate my iOS application with the Apple Remote?

While I believe the title of this question should be clear enough, if you have any doubts about what an Apple Remote is, simply click here. ...

Error Arises When React Components Are Nested within Objects

I'm encountering a peculiar issue with my component. It works perfectly fine when retrieving data from State at a high level, but as soon as I try to access nested objects, it throws an error: "TypeError: Cannot read property 'name' of undef ...

"Implementing a select value in React.js using option values and mapping through iterations, with the

Currently, I am working on a React application where I encountered an issue with the map method during iteration. I have a select box that needs to be filled with numbers ranging from 0 to a specified value. My expected output should be [{label:0,value:0 ...

Guide on how to reference the Html directory using the path module in Node Js

Desperately trying to send an html file as a response using express, but I'm having trouble locating the position or path of the index.html file. This is how my files are structured - MyWebsite Html index.html Css index.css ...

Exploring NextJS with Typescript to utilize the getStaticProps method

I'm currently enrolled in a NextJS course and I am interested in using Typescript. While browsing through a GitHub discussion forum, I came across an issue that I don't quite understand. The first function provided below seems to be throwing an e ...

Excessive alerts being produced within the loop

I am trying to remove a wine from a JSON wine list and I want to display an alert if the wine doesn't exist in the JSON file. However, the alert is popping up for every entry in the list. I am struggling to find a way to use an if statement before pro ...

Trouble with Updating InnerHTML

xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", "myurlhere.php", true ); xmlHttp.send(); var display = document.getElementById("display"); display.innerHTML = xmlHttp.response; This snippet of code is part of a function triggered by a button click. ...

Is HTML5 local storage not functioning properly on IE11 in Windows 8.1 x64? Encountering an error message:

Is anyone else experiencing this issue where information cannot be found, even though it was previously fixed in a patch a long time ago? Has anyone else encountered this? localStorage.setItem("hello", "somedata"); alert(localStorage.getItem(" ...

Issues with Angular route links not functioning correctly when using an Array of objects

After hard coding some routerLinks into my application and witnessing smooth functionality, I decided to explore a different approach: View: <ul class="list navbar-nav"></ul> Ts.file public links = [ { name: "Home&quo ...

What is the best way to determine and showcase the hours that have passed since the user's initial visit to the website?

Can someone provide guidance on how to finalize the hoursSinceFirstVisit() function implementation? Additionally, what content should be displayed on my HTML page? $(document).ready(function() { startTimer(); }); function startTimer() { setInte ...

What is the most effective method for achieving a desired outcome?

Is it a valid approach to get an action result, and if so, how can this be achieved? For instance, if there is a page with a form for creating entities, after successfully creating an entity, the user should be redirected to the entity's detail view. ...

Connecting an HTML box to a JavaScript function for the desired outcome: How to do it?

My goal is to connect the input box with id="b" (located inside the div with id="but1") with a JavaScript function that calculates values within an array. Although my junior logic review didn't detect any issues in the code, what mistakes could I have ...

Is it feasible to arrange <DIV>s based on their dates?

I encountered an issue while working with an ordering function. var $wrapper = $('#list'); $wrapper.find('.blogboxes').sort(function (a, b) { return +b.dataset.date - +a.dataset.date; }) .appendTo( $wrapper ); <script src="ht ...

Postman Guide: Mastering the Evaluation of JSON Arrays

One of the features in Postman allows users to save a specific field from the response body as a variable and then utilize that variable in a subsequent call. For instance, after my initial call to the web service, the response body contains: [ { "id" ...

Send data from one API function to another function in Flask

Trying to pass a list from one API function to another @app.route('/get_output',methods = ['GET','POST']) def input_function(): data_list=['1','2','3','4'] status='success& ...

If the cursor hovers over an image, the onmouseover function does not work properly

Currently, I am developing a PHP page to display data from a database in a tabular format. Each column in the table represents an 'ATC Station'. When active, additional data is displayed upon hovering over the cell. Everything was running smooth ...