2017-07-03 81 views
0

我有一个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) 
     } 
    }) 
    }) 
}) 

编辑: 感谢杰克逊暗示我设法做这样。

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) 
     } 
    }) 
    }) 
}) 
+0

如果要更新的文件,[更新](http://mongoosejs.com/docs/api.html#model_Model.update)它,不要保存它。 –

回答

1
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 { 

    } 
}) 
+0

谢谢杰克逊。我设法做到了。检查完成时是否(req.body.completed)不起作用是错误的,我需要将其更改为true。相反,我用if(req.body.completed!== undefined) –

+0

是的,我错过了null,false,0 :) – Jackson