用猫鼬更新字段子集

时间:2019-11-28 17:18:46

标签: node.js mongodb express mongoose

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

1 个答案:

答案 0 :(得分:1)

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

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