Implement Update User Service

We will support both PUT and PATCH operations.

For PUT, the request should provide the complete set of editable user fields.

For PATCH, only the supplied fields should be updated.

Mongoose provides findByIdAndUpdate() for updating a document by its ID.

Use the new option to return the updated document and runValidators to apply schema validators during the update.

Never Pass the Entire Request Body Blindly

Only allow explicitly editable fields. Never allow clients to update protected fields such as role, password hashes, or internal account status through a general-purpose update endpoint.

Update User Service
export async function updateUser(userId, updateData) {
  return User.findByIdAndUpdate(
    userId,
    { $set: updateData },
    {
      new: true,
      runValidators: true
    }
  ).select('-password');
}

Updates the supplied fields and returns the updated document. runValidators enables schema validation for supported update operations.

Key Takeaways
  • findByIdAndUpdate() updates documents by identifier.

  • runValidators enables update validation.

  • Use an explicit allowlist of editable properties.