Is it possible to update my array using a put request?

I am having trouble updating the objects in my array and I need to be able to call them in Postman with a new value attached to the item I'm referencing. This is an assignment that is due today, so please help me.

Check out this screenshot from Postman

const express = require("express");
const {emitWarning} = require("process");
// Setting up Express
const app = express()
// Defining port number 8081
const PORT = 8081;
// Listening on designated port
app.listen(PORT, () => console.log("Server is listening on port 8080"))


//Task B
// Creating an array with categories and quantities
var livestock = [

  {id:0, category: 'Cows', quantity: 50 },
   {id:1, category: 'Dogs', quantity: 1 },
   {id:2, category: 'Pigs', quantity: 100 },
   {id: 3, category: 'Sheep', quantity: 20 },
];
app.put('/update_livestock/:category/:quantity', (req, res)=> {
 if (req.params.category in livestock){
   livestock[req.params.category] = req.params.quantity;
   res.json(livestock);
 } else{
   res.sendStatus(404)
 }
});

Answer №1

It appears that you are attempting to access an array of objects as if it were an array of strings.

Consider making this change:

const result = besatning.find(item => item.kategori === req.params.kategori);
if (result) {
    res.json(result);
} else {
    res.sendStatus(404);
}

This code will retrieve the matching item. Remember to make a GET request when using this endpoint.

For updating an item, typically by its id, use a PUT request. Your URL should look something like "/ny_besætning/:id" and utilize a find filter to locate the item by its id. When updating the item, ensure to send the updated object in the payload format (e.g., body tag in Postman) as a complete object like: {id:0, kategori: 'updated', antal: 9999 }

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

The AJAX response enters a continuous loop if it contains the window.print function

I'm looking to print the screen upon receiving an ajax response. Here's my code snippet: function initiatePrint() { var request = new XMLHttpRequest(); request .open("GET", "printPage.html", true); var counter = 0; ...

Preventing a JavaScript timer function from executing multiple times when triggered by an 'in viewport' function

I am trying to create a website feature where a timer starts counting up once a specific div is scrolled into view. However, I am encountering an issue where scrolling away restarts the timer, and I would like the final value that the timer reaches to rema ...

Discovering the culprit causing a freeze on your page: Uncovering the tool or technique to identify the problematic

What is the best tool to identify resource-heavy or infinite loop JavaScript/jQuery scripts? I am currently experiencing issues with a specific template: When I open this page on Firefox 46.0.1, it freezes after a few minutes. I am having trouble pinpoin ...

Execute operations on element itself rather than the output of document.getElementbyId

I encountered an issue involving an HTML element with the ID of BaseGridView. When I call a function directly on this element, everything works perfectly. However, if I use document.getElementById() to retrieve the element and then call the function, it do ...

The onclick value within a loop is only effective for the final value in the table

As someone who is new to Javascript, I am embarking on the journey of creating a unit conversion calculator. My goal is to loop through a table and assign an onclick event that will display the value of the clicked button. So far, I've managed to obt ...

Is there a method in TypeScript to make an enum more dynamic by parameterizing it?

I've defined this enum in our codebase. enum EventDesc { EVENT1 = 'event 1', EVENT2 = 'event 2', EVENT3 = 'event 3' } The backend has EVENT1, EVENT2, EVENT3 as event types. On the UI, we display event 1, event 2, a ...

What is the possible reason behind the Vue warning message: "The instance is referencing the 'msg' property or method during rendering, even though it is not defined"?

Although the situation seems straightforward, the reason behind it is not clear to me. I am attempting to create a Vue component for a project with older ES5 code. The Vue library version I am using is 2.6x (I also tried 2.5x). Here is the Vue component I ...

Email JS indicating that the provided Public Key is invalid

I'm currently utilizing email js for handling form submissions in React, and encountered this notification: "The Public Key is invalid. For the correct ID, please visit here, " Although I've double-checked the public key, I seem to b ...

Tips for sending a Postgres Pool or Client over a socket

After deploying my server to Heroku, I encountered an issue with sending a request to my Raspberry Pi for running a scraping function and updating a table in the Heroku Postgres database. The problem seems to be related to the client.query() function not b ...

The ajax request functions smoothly on the OS X Paw app and cURL, but does not work properly when coded in Javascript / jQuery

Currently delving into the world of ajax requests, I've been utilizing the Paw app to troubleshoot one. Surprisingly, the request functions flawlessly within Paw itself and even the cURL code generated by Paw works like a charm. However, the JavaScrip ...

Is there any latest feature in .Net 4.5 for enhancing JSON processing capabilities?

Are there any updates in .NET 4.5 and VS2012 for JSON handling that could outperform DataContractJsonSerializer? I've heard about System.JSON, but is it an improvement? I'm aware of JSON.NET as well, but unsure if I can include another .dll in m ...

Nuxt middleware failing to verify user's logged-in status

I am currently working on implementing user authentication and redirection logic based on the user's authentication status. For instance, if a logged-in user tries to access the login or signup page, they should be automatically redirected. To achieve ...

Having trouble assigning the class property in Angular 5

Upon loading the page, a list of products is retrieved from an external JSON source. Each product in the list has a corresponding BUY button displayed alongside it, with the ID of the respective product assigned to the button. The intention is that when a ...

What methods can be used to determine if a session is still active? Are there specific techniques that are effective for verifying session status?

After my initial experience with Web Design, I realized that the way I handled sessions wasn't efficient due to time constraints. I need advice on how to properly handle sessions in web development. In my previous project, I used PHP embedded within H ...

Await keyword cannot be used due to undefined object reference

Currently in the process of implementing authentication into my node API. Using PassportJS, although I am fairly new to this so please bear with me. The goal is to add a local strategy and verify the user's password during login: // Local Strategy ...

Guide on updating a single element in a Firebase array

I have an array stored in my firebase database, structured like this: matches:[ {match:{id:1,data:...}}] I am looking for a way to update just one specific item within this array. Let's say I want to locate the match with the ID of 32 and modify its ...

Error caused by Gson Overflow

While attempting to convert a Json string into a Java object using the Gson library, I encountered a StackOverflowException. java.lang.StackOverflowError com.google.gson.internal.$Gson$Types.checkNotPrimitive($Gson$Types.java:431) com.google.gson ...

Encountering difficulty importing TypeScript files dynamically within a Deno executable

When attempting to import a file from aws in an exe using its public link based on user input, I am facing difficulties For example, I generated my exe with the command below deno compile --allow-all main.ts Users execute this exe using commands like ./e ...

Does Express restrict multiple pending requests from a single IP address?

I am currently developing a chat application that utilizes long polling with express. While I am aware that websockets are considered better for this purpose, I wanted to challenge myself by specifically implementing long polling. When a client is waiting ...

adjusting the height of a div using jQuery UI's layout feature

Recently, I have been playing around with the adjustable grids plugin (jquery ui layout) to set the width of each div using the plugins. However, I've encountered a challenge when it comes to adjusting the height of inner divs within the layout. Speci ...