"Mastering the art of traversing through request.body and making necessary updates on an object

As I was reviewing a MERN tutorial, specifically focusing on the "update" route, I came across some interesting code snippets.

todoRoutes.route('/update/:id').post(function(req, res) {
    Todo.findById(req.params.id, function(err, todo) {
        if (!todo)
            res.status(404).send("data is not found");
        else
            todo.todo_description = req.body.todo_description;
            todo.todo_responsible = req.body.todo_responsible;
            todo.todo_priority = req.body.todo_priority;
            todo.todo_completed = req.body.todo_completed;            
            todo.save().then(todo => {
                res.json('Todo updated!');
            })
            .catch(err => {
                res.status(400).send("Update not possible");
            });
    });
});

The schema utilized by the database:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Todo = new Schema({
    todo_description: {
        type: String
    },
    todo_responsible: {
        type: String
    },
    todo_priority: {
        type: String
    },
    todo_completed: {
        type: Boolean
    }
});
module.exports = mongoose.model('Todo', Todo);

I am seeking a way to automate the updating process in a loop, without needing to adjust the route each time the schema changes.

  • Is it feasible to accomplish something like the following (using Python pseudo-code):

      for param in req.body:
          setattr(todo, param.name, param.value)
          # where param example might be an object with these 2 fields ('name', 'value')
    

    This is my current attempt:

      todoRoutes.route('/update/:id').post(function(req, res) {
          Todo.findById(req.params.id, function(err, todo) {
              if (!todo)
                  res.status(404).send("Data is not found");
              else
                  req.body.forEach(function (item) {
                      todo.setAttribute(req.body.getAttribute(item));
                  });
    
                  todo.save().then(todo => {
                      res.json('Item updated!');
                  }).catch(err => {
                      res.status(400).send("Update not possible: " + err);
                  });
          });
      });
    

Answer №1

To efficiently update a todo item, you can store the object in a single variable before making any changes. Only the modifications that are submitted will be saved.

/**
 * Function to update a todo item
 */
// Importing the todo model
const Todo = require("../models/todo");

async function updateTodo(req, res) {
    const { id } = req.params; // Retrieving the todo id from the request parameters
    const todoData = req.body; // Storing the updated data in a single variable

    try {
        const todoUpdated = await Todo.findByIdAndUpdate(id, todoData);
        if (!todoUpdated) {
            return res.status(404).send('Todo not found');
        }

        return res.status(200).send('Todo updated successfully');
    } catch (err) {
        return res.status(500).send(err);
    }
}

module.exports = {
    updateTodo
};

Answer №2

After reviewing the response from @D4ITON, I decided to test out this code snippet myself and it turned out to be effective:

todoRoutes.route('/modify/:id').post(function(req, res) {
    Todo.findByIdAndUpdate(req.params.id, req.body, function(err, todo) {
        todo.save().then(todo => {
            res.json('Item has been successfully updated!');
        }).catch(err => {
            res.status(400).send("Unable to update: " + 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

Unending React cycles - invoking setState() within a render onClick

Recently delving into React and facing an issue with rendering a button component. My goal is to create a button that, upon being clicked, fetches data and displays it as a list below the button. To achieve this, I am attempting conditional rendering. I ut ...

Displaying nested JSON data in a user interface using React

I have a complex nested JSON structure that I am using to build a user interface. While I have successfully implemented the first part, I am encountering difficulties with the second part. My Objective The nested JSON displays parent elements and now I a ...

Easily modify and manage state on-the-fly using TextFields

Is the title conveying my intentions clearly? If not, please let me know. Essentially, I am looking to create a component that generates a form based on a JSON file. For example, if someone clicks on "light" in the navbar, I want the form to display fields ...

Turn off the nicescroll scroll bar that appears as a default feature

Is there a way to disable the nicescroll scroll bar that appears in red by default on my html page? It's causing issues with zooming in and breaking the layout. ...

JavaScript nested function that returns the ID of the first div element only upon being clicked

I am facing an issue with a function that returns the id of the first div in a post when an ajax call is made. The problem is that it repeats the same id for all subsequent elements or div tags. However, when the function is used on click with specified ...

Passing a JavaScript object that may be undefined to a pug template in Node.js

My journey requires transferring a set of JavaScript objects to the pug template. router.get('/edit/:itemObjectId', async function(req, res, next) { var itemObjectId = req.params.itemObjectId; var equipmentCategoryArr = []; var lifeE ...

Managing key presses with functions in VueJs

Within my component, I am utilizing VueStrap's modal in the following manner: <template> <modal-window v-model="show" v-on:keyup="keyHandler($event)" @ok="submit()" @cancel="cancel()" @closed=" ...

What is the best way to define a variable that captures and logs the values from multiple input variables?

Hey there, I'm a new coder working on a shopping list app. I'm trying to display the input from three fields - "item", "store", and "date" - at the bottom of the page as a single line item. I attempted to do this by creating a variable called "t ...

Using Javascript to replace elements with input fields and text areas

I'm currently working on a unique project for my Wordpress blog, where I am developing a custom block editor using JavaScript on the frontend. The goal is to convert all elements from the post content into a series of inputs and textareas. To begin, ...

Navigating Svelte using Express in a Node.js environment

Greetings, I have a somewhat hesitant question that I haven't been able to find an answer to online: Currently, I am operating a nodejs express Server which is responsible for rendering my views. Here is an example of how it's done: router.get( ...

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

Automatically calculate the multiplication of a number by 10 in React JS within the State

In this scenario, I am looking for assistance in creating a functionality where the user can adjust numbers in an input box and see the result of that number multiplied by 10 in a nearby span element. However, I am encountering issues with fetching the des ...

Database Submission of Newsletter Information

I recently grabbed the following code snippet from a YouTube tutorial (shoutout to pbj746). Everything appears to be functioning correctly except for one crucial issue - the submitted data isn't showing up in the database! I've thoroughly checked ...

Searching in real-time with ajax in CodeIgniter framework is a seamless and efficient process

I'm a beginner in CodeIgniter and eager to learn. Currently, I'm facing an issue where the data is not being populated on the search page. In the model: function fetch_data($query) { $this->db->select('*'); $this-> ...

HTML5 canvas processing causing web worker to run out of memory

Within the Main thread: The source image array is obtained using the getImageData method. It is represented as a uint8ClampedArray to store the image data. Below is the code executed in a web worker: (This operation generates a high-resolution image, but ...

Changing colors in the rows of a table

Here is a fiddle I created to demonstrate my issue. https://jsfiddle.net/7w3c384f/8/ In the fiddle, you can see that my numbered list has alternating colors achieved through the following jQuery code: $(document).ready(function(){ $("tr:even").css("ba ...

Utilizing Node.js callback for validating JWT tokens

In my Node.js server, I have set up an authentication route to authenticate requests: app.get('/loggedin', auth, function(req, res){ console.log(req.authenticated); res.send(req.authenticated ? req.authenticated: false) }) From what I u ...

Redirecting in AngularJS after a successful login操作

Is there a way to redirect users back to the original page after they login? For example, if a user is on a post like www.example.com/post/435 and needs to log in to "like/comment" on the post, how can I automatically redirect them back to that specific po ...

What is the best way to configure multiple environmental variables in webpack?

I'm having trouble figuring out how to pass multiple environment variables to webpack. I've been attempting to execute the script below, but it doesn't seem to be working: "cross-env NODE_ENV=production DTM_ENV=staging webpack --config ...

In order to enhance your programming skills, avoid hard coding functions and ensure that data is returned after binding changes

I am trying to create a method where I can provide a DOM as a parameter and retrieve data from image_preview. The goal is to make image_preview reusable instead of hardcoding it inside the function. Additionally, I want to separate image_preview.model() an ...