"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

Can you tell me the proper term for the element that allows CSS properties to be changed after a link has been clicked?

I have integrated a horizontal scrolling date selector on my website, and it is functioning well. However, I am facing an issue while trying to change the CSS properties of a clicked date link using jQuery. Despite successfully firing the click event, I am ...

Uploading files in chunks using a combination of HTML, JavaScript,

I've been using a file chunking solution (although I can't recall its origin), but I've made some modifications to suit my requirements. Most of the time, the file uploads successfully; however, there are instances where an error occurs. U ...

How does the "deliver_order" function retrieve the value of the name parameter?

function take_order(name, callback1) { console.log("order has been taken."); callback1(name); } function prosess_order(name, callback2) { console.log(`prosesing order for ${name}.`); callback2(name); } function deliver_order(name) { console.log ...

Issues arise when attempting to delete messages that have already been retrieved

Having trouble removing messages from a specific user without any success: bot.js client.on("message", (message) => { if (message.content === '$deleteuser') { message.channel.fetchMessages({limit: 10}).then(collec ...

Removing an element from the parent/master array after splicing the copied array

My array setup includes a master array called the parent array. When the page loads, a PHP array encoded in JSON with information about every user on the site is assigned to a JavaScript variable - var all_users = <?php echo $users;?>;. Upon logging ...

Vanishing elements when employing the react-router library in a React project

Currently, I am in the process of developing a React application and have encountered an issue with components disappearing upon refresh. It seems to be related to React Router, suggesting that I may be implementing it incorrectly. This is what my App.js ...

Utilize the arrow keys to navigate through the search suggestions

I am facing an issue with my search bar where I am unable to navigate through the suggestions using arrow keys. I have been struggling with this problem for days and would appreciate any help in resolving it. var searchIndex = ["404 Error", "Address Bar ...

After running javascript, Elements do not retain any values

I have encountered an issue with two button click events - one is in Javascript and the other in VB. The first button (Javascript) retrieves values from various controls like textboxes and dropdown lists, while the second button (VB) saves these values to ...

Is it possible to save the current permissions for a channel or category in Discord.js and then restore them after a certain event occurs?

A Little Background I recently came across a lockdown command on YT that locks down all channels in the guild when you type "!lockdown". This command overwrites channel permissions for specific roles. However, when we unlock the channels, everyone is able ...

Limit the velocity of an object in Box2D using JavaScript

In my Box2D simulation, a collection of dynamic objects is experiencing various random forces. Is there a way to set a maximum speed for each object (both translational and rotational)? I considered implementing a workaround, but I'm curious if the e ...

Exploring javascript Object iteration with arrays using Python

When users click the "done" button on a text box, all input is stored in an associative array and sent to a Python method. The data is then converted to JSON before being sent via AJAX: $.ajax({ url: "http://127.0.0.1:6543/create_device", ...

Error: VueJS mixins do not include the property definition

I've been trying to incorporate Mixins into my Vue.js code, but I've run into a few issues :/ Here's the current code for two test modules : ErrorBaseMixin.vue <script> import ErrorAlert from './ErrorAlert'; expor ...

Can the tooltip on c3 charts be modified dynamically?

Creating a c3 chart involves defining various properties, including a tooltip. Here is an example: generateData = () => { const x = randomNR(0, 100); const y = randomNR(0, 100); const together = x + y; return { data: { columns: [ ...

Is it possible to examine a Mongoose schema in order to ascertain if a specific field is mandatory?

I have a Mongoose schema that looks like this: var PersonSchema = new Schema({ name : { first: { type: String, required: true } , last: { type: String, required: true } } ... I want to examine the schema in order to determine which ...

dynamic jquery checkbox limit

I am working with the following HTML code: <input type="checkbox" id="perlengkapans" data-stok="[1]" onchange="ambil($(this))"> name item 1 <input type="checkbox" id="perlengkapans" data-stok="[4]" onchange="ambil($(this))"> name item 2 &l ...

Disallow users from closing the tab or browser window

Is it feasible to create a loop on window.onbeforeunload that opens the current page repeatedly upon tab exit? Take a look at the code below - it works, but browsers may block it as a popup. window.onbeforeunload = function(e) { window.open(do ...

List of nested objects converted into a flat array of objects

Looking to transform a data structure from an array of objects containing objects to an objects in array setup using JavaScript/Typescript. Input: [ { "a": "Content A", "b": { "1": "Content ...

View the edited image preview instantly upon selecting the image

I have selected an image and previewed it before submitting the form. However, now I wish to be able to edit the file immediately after selecting it, preview the changes, and then submit the file. <input type ="file" accept="image/*" id="image" name="i ...

Ways to guarantee that a function runs prior to a console.log in Mongoose

I've created a function called findUser that I'm working on implementing using sails, MongoDb, and mongoose. Here's what the function looks like: findUser(userId); function findUser(user_id){ User.findOne({ _id: user_id ...

Utilize [markdown links](https://www.markdownguide.org/basic-syntax/#

I have a lengthy text saved in a string and I am looking to swap out certain words in the text with a highlighted version or a markdown link that directs to a glossary page explaining those specific words. The words needing replacement are contained within ...