首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据可变请求数据智能地更新Mongoose文档?

如何根据可变请求数据智能地更新Mongoose文档?
EN

Stack Overflow用户
提问于 2019-06-20 02:09:46
回答 1查看 23关注 0票数 0

对于我的编辑用户路由,我将需要处理许多不同的可能情况。用户可以更新他们的配置文件,只更改他们的电子邮件地址或密码,但他们也可能同时更新整个范围的其他配置文件信息。

findOneAndUpdate的优点是您可以传递update对象,并且它只会更改与保存的数据不同的请求中的那些字段。这太棒了!一个巨大的问题--这个查询出于某种原因绕过了验证器和中间件(即使使用runValidators=true,它也绕过预保存钩子,这意味着密码更新绕过了加密)。

因此,我一直看到的解决方案是执行findOnefindById,手动更新字段,然后运行user.save()

但是,使用相当复杂的用户记录,这意味着我的路由将类似于此,很难维护:

代码语言:javascript
复制
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,让它只更新不同的字段?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-20 15:40:16

https://lodash.com/docs/4.17.11#merge

_.merge(用户,req.body)

这将合并**所有**。只有在你不关心安全的情况下才使用。

在没有疯狂的情况下限制在某些领域:

代码语言:javascript
复制
const { f1, f2, f3 } = req.body;
_.merge(user, { f1, f2, f3}) 

或参考以下内容:https://lodash.com/docs/4.17.11#pick

有点不明显的特点,在房客。

代码语言:javascript
复制
_.merge(user, _.pick(req.body, ['f1', 'f2', 'f3']))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56678087

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档