Mongoose FindOneandUpdate - Only update Specific fields leave others with the previous values

Viewed 97

I would like to update just the fields that the user chose to update, but right now if I don't fill all the inputs, they became null in the data base. this is the back end

router.put('/user/:id', async (req, res) => {
    let id = req.params.id
    const salt = await bcrypt.genSalt(10)
    const hashPassword = await bcrypt.hash(req.body.password, salt)
    const emailExist = await User.findOne({ email: req.body.email })
    if (emailExist) {
        return res.status(400).send('Email already exists')
    }
    //creat user
    const update = {
        name: req.body.name,
        lastName: req.body.lastName,
        phone: req.body.phone,
        email: req.body.email,
        bio: req.body.bio,
        password: hashPassword,
        role: "basic"

    }
    User.findByIdAndUpdate(id, { $set: update }, { new: true }, (error, userObj) => {
        if (error) {
            res.status(400).send(err)
        } else {
            res.send('user updated')
        }
    })
})

Front end (react)

const updateUser = async (event) => {
        event.preventDefault()
        const response = await axios.put(`/userinfo/user/${localStorage.getItem('id')}`, {
            name: name,
            lastName: lastName,
            phone: phone,
            email: email,
            password: password,
            confPassword: confPassword,
            bio: bio,
        })

        history.push('/home-login')
        const reload = window.location.reload()
    }

Thank you

1 Answers

Try handy methods of lodash NPM, install it and import in your node.js file,

Pick update fields from body:

let update = _.pick(req.body, ["name", "lastName", "phone", "email", "bio"]);

Remove undefined, null and "" empty fields:

update = _.pickBy(update, _.identity);

Merge other fields:

update = _.merge(update, {
    password: hashPassword,
    role: "basic"
});

Use in query:

User.findByIdAndUpdate(id, { $set: update }, { new: true }, (error, userObj) => {
  if (error) res.status(400).send(err)
  else res.send('user updated')
})
Related