Skip to content

Commit

Permalink
fix(backend/services): Preserve existing settings when updating user …
Browse files Browse the repository at this point in the history
…settings

- Updated `updateSettingsById` function in `userService.js` to preserve existing settings when updating user settings.
- Ensured only provided settings fields are updated, leaving other fields unchanged.
- Validated and applied partial updates to the `settings` subdocument.
  • Loading branch information
TKanX committed Jan 9, 2025
1 parent 3963038 commit 596ad58
Showing 1 changed file with 7 additions and 2 deletions.
9 changes: 7 additions & 2 deletions backend/src/services/userService.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,17 +179,22 @@ const getSettingsById = async (userId) => {
/**
* @function updateSettingsById - Update the settings of a user by ID.
* @param {string} userId - The user's ID.
* @param {Object} settings - The user's settings.
* @param {Object} settings - The user's settings to update.
* @returns {Promise<Object>} - The updated user settings.
* @throws {Error} - Throws an error if the user fails to update.
*/
const updateSettingsById = async (userId, settings) => {
if (!mongoose.Types.ObjectId.isValid(userId)) return null;

const updateFields = {};
for (const key in settings) {
updateFields[`settings.${key}`] = settings[key];
}

try {
const updatedUser = await User.findByIdAndUpdate(
userId,
{ settings },
{ $set: updateFields },
{ new: true, projection: { settings: 1 } },
);
if (!updatedUser) throw new Error('User not found');
Expand Down

0 comments on commit 596ad58

Please sign in to comment.