【发布时间】:2020-03-24 09:37:25
【问题描述】:
当只指定了部分字段时,如何使用 Mongoose 更新 MongoDB 文档? (即更新指定的字段,但保持任何其他现有字段不变)
在以下路由处理程序中,用户可以选择提供哪些字段。以下工作,但使用if 语句感觉不是特别好。有没有更优雅的解决方案?
// Get the user properties from the request body
const { email, firstname, lastname} = req.body;
// Decide what fields to update
const fieldsToUpdate = {
updatedAt: Date.now(),
};
if(email) fieldsToUpdate.email = email;
if(firstname) fieldsToUpdate.firstname = firstname;
if(lastname) fieldsToUpdate.lastname = lastname;
// Update the user object in the db
const userUpdated = await User
.findByIdAndUpdate(
userId,
fieldsToUpdate,
{
new: true,
runValidators: true,
}
);
我尝试过使用email: email 的不同方法,但如果字段未定义或为空,Mongoose 会将null 放入数据库中,而不是保持字段不变?
【问题讨论】:
标签: node.js mongodb express mongoose