Home > database >  How to create an express update route with multiple parameters
How to create an express update route with multiple parameters

Time:04-03


I want to update an attribute within a JSON object using fetch PUT. I've created a put function taking in 2 URL parameters
app.put('/trustRoutes/:id/:item', (req, res){

I am able to update the data with a single parameter but since I only want to change one value inside that object, calling put will replace the whole object with my new body.
below is what I've tried.

app.put('/trustRoutes/:id/:item', (req, res) => {
    readFile(data => {
 
      const userId = req.params['id/item'];
      // have also tried const userId = req.params.id.item
      data[userId] = req.body;
  
//write data back to file 

I looked around at other examples but couldn't find any that were updating data instead of GET. If there is one I missed please let me know.

CodePudding user response:

PUT requests are great for completely overwriting a resource, and is idempotent. This answer does a good job explaining idempotency. For updating a resource partially, a PATCH request is a better choice.

app.patch('/trustRoutes/:id/:item', (req, res) => {
    readFile(data => {
        data[userId] = req.params[id];
        data[item] = req.params[item];
        // A get request for this resource would now show both of the updated values
        // Write file
  • Related