`User.findById()`:方法根据用户 ID 查找当前用户的信息,若用户不存在则返回 404 错误。
`User.findOne()`:方法检查新用户名是否已存在于数据库中。
`User.findByIdAndUpdate()`:方法更新用户信息,`new: true` 表示返回更新后的文档,`runValidators: true` 表示运行模型的验证器。
// 处理用户信息更新的路由app.put("/users/:id", async (req, res) => {try {const userId = req.params.id;const updateData = req.body;// 验证是否为有效的 ObjectIdif (!mongoose.Types.ObjectId.isValid(userId)) {return res.status(400).json({ message: "Invalid user ID" });}// 根据用户 ID 查找当前用户信息const currentUser = await User.findById(userId);if (!currentUser) {return res.status(404).json({ message: "User not found" });}// 检查用户名是否发生变化if (updateData.username && updateData.username !== currentUser.username) {// 验证新用户名是否已存在const existingUser = await User.findOne({username: updateData.username,});if (existingUser) {return res.status(409).json({ message: "Username already exists" });}}// 更新用户信息const updatedUser = await User.findByIdAndUpdate(userId, updateData, {new: true,runValidators: true,});res.json({ message: "User updated successfully", user: updatedUser });} catch (error) {console.error("Error updating user:", error);res.status(500).json({ error: "Internal Server Error" });}});