【问题标题】:Mongoose FindOneandUpdate - Only update Specific fields leave others with the previous valuesMongoose FindOneandUpdate - 仅更新特定字段将其他字段保留为以前的值
【发布时间】:2021-04-12 06:43:27
【问题描述】:

我只想更新用户选择更新的字段,但现在如果我不填写所有输入,它们在数据库中将变为空。 这是后端

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')
        }
    })
})

前端(反应)

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()
    }

谢谢

【问题讨论】:

  • 它们变为空,因为您正在使用所有字段创建 update 对象。只需传递 req.body 而不是 update 对象。

标签: reactjs express mongoose


【解决方案1】:

尝试lodash NPM的便捷方法,安装并导入你的node.js文件,

从正文中选择更新字段:

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

删除未定义的、null 和 "" 空字段:

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

合并其他字段:

update = _.merge(update, {
    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')
})

【讨论】:

    猜你喜欢
    • 2022-12-16
    • 2016-09-13
    • 2016-08-02
    • 2019-09-27
    • 2018-04-19
    • 2019-05-11
    • 2023-03-30
    • 2017-08-25
    • 2021-02-09
    相关资源
    最近更新 更多