Update subset of fields with Mongoose

后端 未结 1 1536
青春惊慌失措
青春惊慌失措 2021-01-23 18:30

How can I update a MongoDB document with Mongoose when only a subset of its fields are specified? (i.e. update the specified fields, but leave any other existing fields

相关标签:
1条回答
  • 2021-01-23 18:52

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

    And use it like this:

      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
      });
    
    0 讨论(0)
提交回复
热议问题