我想只更新用户选择更新的字段,但现在如果我不填写所有输入,它们在数据库中就会变为空。 这是后端
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')
}
})
})
前端( 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()
}
谢谢
最佳答案
尝试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')
})
关于reactjs - Mongoose FindOneandUpdate - 仅更新特定字段,让其他字段保留以前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65597137/