Home > Back-end >  trying to update single entry in mongodb using node js
trying to update single entry in mongodb using node js

Time:09-17

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

CodePudding user response:

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

CodePudding user response:

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 :

  • And check if your id is in the right form. If in your database it is not in bjson with MongoId. If this is the case, do not hesitate to convert your id as realized below.
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 }
  );
};
  • Related