0

I have the following update route:

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

}); 

The issue that I am having is that if I send a request to only update:

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

it also overrides those values not defined and re-sets those values. So if before favoriteFilm, genres, portfolio, etc. had values before, they will be overridden as undefined now. So while I want to keep all other values as they were before, they are now undefined. So the request I really send looks more like:

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

I only want to update the fields specified and leave the other values as is. How do I handle this in a single request?

Thank you!

Ethan
  • 47
  • 1
  • 5

1 Answers1

0

You can use the logical OR (||) operator while assigning the new value

    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, ...

Basically this, will look for a value in the request body if it's truthy (as per JS) then that will be picked otherwise the value of the key in the db object named user will be assigned, please do note, if in case it is not found in the db object user as well, the final value will be undefined.

More about this concept can be found here JavaScript OR (||) variable assignment explanation

Udyan Sharma
  • 134
  • 7