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); }); }); });