猫鼬findByIdAndUpdate我一点都不明白

时间:2019-11-01 17:22:34

标签: mongoose

您好,我遇到findByIdAndUpdate问题。我在做什么错了?

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

2 个答案:

答案 0 :(得分:1)

对不起,我认为我们一点也不了解对方,但是现在可以在您的帮助下使用。那就是最后的代码:

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

});

答案 1 :(得分:0)

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

   });

});

});