用猫鼬更新字段子集 [英] Update subset of fields with Mongoose

查看:79
本文介绍了用猫鼬更新字段子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当仅指定其一部分字段时,如何使用Mongoose更新MongoDB文档? (即更新指定的字段,但保留所有其他现有字段不变)

在以下路由处理程序中,用户可以选择要提供的字段.以下工作有效,但是使用if语句感觉并不特别.有没有更优雅的解决方案?

In the following route handler, the user can choose which fields to provide. The following works, but using the if statements does not feel particularly great. Is there a more elegant solution?

    // 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的另一种方法,但是如果字段未定义或为null,Mongoose会将null放入数据库中而不是保持字段不变?

I have tried a different approach using email: email but if a field is undefined or null, Mongoose will put null in the database instead of leaving the field unchanged?

推荐答案

您可以创建如下的帮助方法:

You can create a helper method like this:

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

这篇关于用猫鼬更新字段子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆