对于我的编辑用户路由,我将需要处理许多不同的可能情况。用户可以更新他们的配置文件,只更改他们的电子邮件地址或密码,但他们也可能同时更新整个范围的其他配置文件信息。
findOneAndUpdate的优点是您可以传递update对象,并且它只会更改与保存的数据不同的请求中的那些字段。这太棒了!一个巨大的问题--这个查询出于某种原因绕过了验证器和中间件(即使使用runValidators=true,它也绕过预保存钩子,这意味着密码更新绕过了加密)。
因此,我一直看到的解决方案是执行findOne或findById,手动更新字段,然后运行user.save()。
但是,使用相当复杂的用户记录,这意味着我的路由将类似于此,很难维护:
exports.editUser = async function(req, res, next) {
try {
const id = req.params.id;
let user = await db.User.findById(id);
user.email = req.body.email;
user.fullName = req.body.fullName;
user.password = req.body.password;
user.otherField = req.body.otherField;
user.otherField = req.body.otherField;
user.otherField = req.body.otherField;
user.otherField = req.body.otherField;
user.otherField = req.body.otherField;
user.otherField = req.body.otherField;
user.otherField = req.body.otherField;
user.otherField = req.body.otherField;
user.otherField = req.body.otherField;
user.otherField = req.body.otherField;
user.otherField = req.body.otherField;
let updatedUser = await user.save();
return res.status('200').json(user);
}有没有任何方法来模仿将更新对象传递给Mongoose的行为,在那里我只给它req.body,让它只更新不同的字段?
发布于 2019-06-20 15:40:16
https://lodash.com/docs/4.17.11#merge
_.merge(用户,req.body)
这将合并**所有**。只有在你不关心安全的情况下才使用。
在没有疯狂的情况下限制在某些领域:
const { f1, f2, f3 } = req.body;
_.merge(user, { f1, f2, f3}) 或参考以下内容:https://lodash.com/docs/4.17.11#pick
有点不明显的特点,在房客。
_.merge(user, _.pick(req.body, ['f1', 'f2', 'f3']))https://stackoverflow.com/questions/56678087
复制相似问题