当仅指定 MongoDB 文档的部分字段时,如何使用 Mongoose 更新该文档? (即更新指定字段,但保留任何其他现有字段不变)
在以下路由处理程序中,用户可以选择要提供的字段。以下作品有效,但使用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
在数据库中而不是保持字段不变?
您可以创建一个像这样的辅助方法:
const filterObj = (obj, ...allowedFields) => {
const newObj = {};
Object.keys(obj).forEach(el => {
if (allowedFields.includes(el) && (typeof obj[el] === "boolean" || obj[el]))
newObj[el] = obj[el];
});
return newObj;
};
并像这样使用它:
let filteredBody = filterObj(req.body, "email", "firstname", "lastname");
filteredBody.updatedAt = Date.now();
// Update the user object in the db
const userUpdated = await User.findByIdAndUpdate(userId, filteredBody, {
new: true,
runValidators: true
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)