-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import { Request, Response } from "express"; | ||
import User from "../model/User"; | ||
|
||
export const updateUser = async (req: Request, res: Response) => { | ||
const { userId } = req.params; | ||
const allowedFields = [ | ||
"firstName", | ||
"lastName", | ||
"username", | ||
"email", | ||
"role", | ||
"workshopIDs", | ||
"menteeInfo", | ||
"meetingSchedule", | ||
"mentorData", | ||
"meetings", | ||
]; | ||
|
||
try { | ||
const updateData: Partial<typeof User> = {}; | ||
Object.keys(req.body).forEach((key) => { | ||
if (allowedFields.includes(key)) { | ||
updateData[key as keyof typeof updateData] = req.body[key]; | ||
} | ||
}); | ||
|
||
if (Object.keys(updateData).length === 0) { | ||
return res | ||
.status(400) | ||
.json({ message: "No valid fields provided for update" }); | ||
} | ||
|
||
const updatedUser = await User.findByIdAndUpdate( | ||
userId, | ||
{ $set: updateData }, | ||
{ new: true, runValidators: true } // Return updated document and validate | ||
); | ||
|
||
if (!updatedUser) { | ||
return res.status(404).json({ message: "User not found" }); | ||
} | ||
|
||
res.status(200).json({ | ||
message: "User updated successfully", | ||
user: updatedUser, | ||
}); | ||
} catch (error) { | ||
console.error("Error updating user:", error); | ||
res.status(500).json({ | ||
message: "Error updating user", | ||
error, | ||
}); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters