提问者:小点点

NodeJS更新路由:仅在定义时更新值


我有以下更新路由:

router.put('/:id', upload.single('userImage'), (req, res) => {
    Users.findById(req.params.id)
        .then(user => {
            user.shareEmail = req.body.shareEmail, 
            user.filmmakerQuestion = req.body.filmmakerQuestion,
            user.genres = req.body.genres,
            user.favoriteFilm = req.body.favoriteFilm,
            user.imbd = req.body.portfolio,
            user.portfolio = req.body.portfolio,
            user.aboutYou = req.body.aboutYou,
            user.userImage = req.file.path 
            
        user 
            .save()
            .then(() => res.json("The User is UPDATED succesfully!"))
            .catch(err => res.status(400).json(`Error: ${err}`)); 
        }) 
        .catch(err => res.status(500).json(`Error: ${err}`));  
        console.log(req.body); 
        console.log(req.file); 

}); 

我遇到的问题是,如果我只发送一个更新请求:

{
"shareEmail": "yes,  
"filmmakerQuestion": "no" 
}

它还会覆盖那些未定义的值,并重新设置那些值。因此,如果favoriteFilm,genres,portfolio等之前有值,它们将被覆盖为未定义。所以,虽然我想保持所有其他值之前的样子,但它们现在是未定义的。所以我真正发送的请求看起来更像:

{
 "shareEmail": "yes,  
"filmmakerQuestion": "no", 
"genres": undefined, 
"favoriteFilm": undefined, 
"imbd": undefined, 
"aboutYou": undefined, 
"userImage" : undefined
}

我只想更新指定的字段,其他值保持不变。如何在单个请求中处理此问题?

谢谢!


共1个答案

匿名用户

您可以在分配新值时使用逻辑OR()运算符

    user.shareEmail = req.body.shareEmail || user.shareEmail, 
    user.filmmakerQuestion = req.body.filmmakerQuestion || user.filmmakerQuestion,
    user.genres = req.body.genres || user.genres,
    user.favoriteFilm = req.body.favoriteFilm || user.favoriteFilm, ...

基本上,这将在请求体中寻找一个值,如果它是真实的(根据JS),那么它将被选中,否则将分配名为user的db对象中的键值,请注意,如果在db对象user中没有找到它,那么最终的值将未定义。

关于这个概念的更多信息可以在JavaScript或()变量赋值解释中找到