const updateTask = async (req, res) => {
const { id } = req.params;
let update = {};
if (req.body.taskTitle) update.taskTitle = req.body.taskTitle;
if (req.body.taskContent) update.taskContent = req.body.taskContent;
if (req.body.role) update.role = req.body.role;
let task = await Task.updateOne(
{ taskId: id },
{
$set: {
update,
},
},
{ runValidators: true }
);
};
This is my code to update my data in database
as I am trying to update single single data or key if I want to update single data but it's not updating any thing i don't know where its not working as i tried to console data data come perfectly
what the variable Task is ? And I’m sorry, but I didn’t really understand your question, so could you rephrase it more clearly ?
If not, be careful, users might inject things into your database. You should use the mongo-sanitize script.
Like that :
const sanitize = require('mongo-sanitize');
const mongo = require('mongodb');
const updateTask = async (req, res) => {
const { id } = req.params;
let update = {};
if (req.body.taskTitle) update.taskTitle = sanitize(req.body.taskTitle);
if (req.body.taskContent) update.taskContent = sanitize(req.body.taskContent);
if (req.body.role) update.role = sanitize(req.body.role);
let task = await Task.updateOne(
{ taskId: mongo.ObjectId(sanitize(id)) }, // You can remove the mongo.ObjectId if your id is not a objectid.
{
$set: {
update,
},
},
{ runValidators: true }
);
};
const updateTask = async (req, res) => {
const { id } = req.params;
let update = {};
if (req.body.taskTitle) update.taskTitle = req.body.taskTitle;
if (req.body.taskContent) update.taskContent = req.body.taskContent;
if (req.body.role) update.role = req.body.role;
let task = await Task.updateOne(
{ taskId: id },
{
$set: update,
},
{ runValidators: true }
);
};
all you have to do was remove curly brackets and it will work like a charm $set : update