Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs Mongoose FindOneandUpdate-仅更新特定字段,其他字段保留以前的值_Reactjs_Express_Mongoose - Fatal编程技术网

Reactjs Mongoose FindOneandUpdate-仅更新特定字段,其他字段保留以前的值

Reactjs Mongoose FindOneandUpdate-仅更新特定字段,其他字段保留以前的值,reactjs,express,mongoose,Reactjs,Express,Mongoose,我只想更新用户选择更新的字段,但现在如果我不填写所有输入,它们在数据库中就会变成空。 这是后端 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 emailE

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

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

前端(反应)

谢谢你

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

它们变为null,因为您正在创建包含所有字段的
update
对象。只需传递
req.body
而不是
update
对象。
User.findByIdAndUpdate(id, { $set: update }, { new: true }, (error, userObj) => {
  if (error) res.status(400).send(err)
  else res.send('user updated')
})