Wojtas
Wojtas

Reputation: 13

mongoose findByIdAndUpdate i dont understand it at all

Hi i got a problem with findByIdAndUpdate. What I am doing wrong?

router.post('/add/:id', function(req, res) {
  const body = req.body;
  const task = NewTask(body);
  console.log(task);
  console.log(task.id);
  const updateObj = {
    description: task.description,
    selectValue: task.selectValue,
    timeToDo: task.timeToDo
  };
  console.log('Object:', updateObj);
  NewTask.findByIdAndUpdate(task.id, updateObj, { new: true });

  res.redirect('/tasks');
});

Upvotes: 0

Views: 37

Answers (2)

Wojtas
Wojtas

Reputation: 13

Sorry i think we didn't understand each other at all, but it works with your help now. Thats the finally code :

router.post('/add/:id', function (req, res) {
const body = req.body;
const id = req.params.id;
const updateObj = {
    description: body.description,
    selectValue: body.selectValue,
    timeToDo: body.timeToDo
};

console.log('Object:', updateObj);
NewTask.findByIdAndUpdate(id, updateObj, { new: true }, (err, doc) => {
    if (err) {
        console.log('There was an error updating task');
    } else {
        res.redirect('/tasks');
    }
});

});

Upvotes: 1

Thabo
Thabo

Reputation: 1475

router.post('/add/:id', function (req, res) {
   const body = req.body;
   const task = new NewTask(body);

   task.save((err, task) => {
   if(err) {
    console.log('There was an error saving the tack');
   } else {
     res.redirect('/tasks');
   }
 });
});

 router.post('/update/:id', function (req, res) {
   const body = req.body;
   const id = req.params.id;

   const updateObj = {
     description: body.description,
     selectValue: body.selectValue,
     timeToDo: body.timeToDo
   };

    console.log('Object:', updateObj);
    NewTask.findByIdAndUpdate(id, updateObj, { new: true }, (err, doc) => {
   if(err) {
    console.log('There was an error updating task');
   } else {
     res.redirect('/tasks');
   }

   });

});

});

Upvotes: 0

Related Questions