Mongoose 仅​​更新已更改的值

Igo*_*Vuk 5 routes mongoose mongodb express

我有一个 PUT 路由来更新值。我从两个地方走这条路线。一种是发送有关详细信息的信息,另一种是发送有关已完成的信息。问题是猫鼬正在更新展位,尽管它只从一个展位获得价值。

因此,如果我发送有关已完成的信息,它是真的,后来我使用新的详细信息(没有已完成的值)点击此路线,它也会将已完成更新为假。如何仅更新已更改的值?

router.put('/:id', (req, res) => {
  Todo.findOne({_id:req.body.id}, (err, foundObject) => {
      foundObject.details = req.body.details
      foundObject.completed = req.body.completed
    foundObject.save((e, updatedTodo) => {
      if(err) {
        res.status(400).send(e)
      } else {
        res.send(updatedTodo)
      }
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

编辑: 感谢杰克逊的暗示我才得以做到这一点。

router.put('/:id', (req, res) => {
  Todo.findOne({_id:req.body.id}, (err, foundObject) => {
    if(req.body.details !== undefined) {
      foundObject.details = req.body.details
    }
    if(req.body.completed !== undefined) {
      foundObject.completed = req.body.completed
    }
    foundObject.save((e, updatedTodo) => {
      if(err) {
        res.status(400).send(e)
      } else {
        res.send(updatedTodo)
      }
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

Jac*_*son 9

const updateQuery = {};

if (req.body.details) {
  updateQuery.details = req.body.details
}

if (req.body.completed) {
  updateQuery.completed = req.body.completed
}

//or
Todo.findOneAndUpdate({id: req.body.id}, updateQuery, {new: true}, (err, res) => {
  if (err) {

  } else {

  }
})

//or
Todo.findOneAndUpdate({id: req.body.id}, {$set: updateQuery}, {new: true}, (err, res) => {
  if (err) {

  } else {

  }
})
Run Code Online (Sandbox Code Playgroud)