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