【问题标题】:Update subset of fields with Mongoose使用 Mongoose 更新字段子集
【发布时间】:2020-03-24 09:37:25
【问题描述】:

当只指定了部分字段时,如何使用 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 的不同方法,但如果字段未定义或为空,Mongoose 会将null 放入数据库中,而不是保持字段不变?

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案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
      });
    

    【讨论】:

    • 太棒了,非常感谢!我假设filterObj.updatedAtfilteredBody.updated at?如果是这样,您能否解决这个问题,以便我接受您的回答?
    • 如果我想在多个控制器中使用这个辅助函数,放在哪里比较好? (即它不是路由,不是控制器,不是中间件,不是模型等 - 它去哪里了?)
    • @Ben 这个方法最好放在一个 util 文件中。
    • 我不是这个意思。第二个代码示例的第 2 行中的 filterObj.updatedAt 必须是 filteredBody.updatedAt,因为您将 filteredBody 传递给 findByIdAndUpdate
    • @Ben 是的,你是对的,我在答案中更正了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 2020-04-04
    • 2021-07-09
    • 2021-06-21
    • 2021-01-10
    • 2016-09-13
    • 2015-06-10
    相关资源
    最近更新 更多