Express + MongoDB 实现更新用户时用户名变化验证数据库是否存在,不变不验证

**`User.findById()`:**方法根据用户 ID 查找当前用户的信息,若用户不存在则返回 404 错误。

**`User.findOne()`:**方法检查新用户名是否已存在于数据库中。

`User.findByIdAndUpdate()`: 方法更新用户信息,`new: true` 表示返回更新后的文档,**`runValidators: true`**表示运行模型的验证器。

javascript 复制代码
// 处理用户信息更新的路由

app.put("/users/:id", async (req, res) => {

  try {

    const userId = req.params.id;

    const updateData = req.body;

    // 验证是否为有效的 ObjectId

    if (!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" });

  }

});
相关推荐
苏宸啊22 分钟前
Linux权限
linux·运维·服务器
正在走向自律27 分钟前
金仓数据库KingbaseES中级语法详解与实践指南
数据库·oracle·kingbasees·金仓数据库·信创改造
Gofarlic_oms133 分钟前
Windchill用户登录与模块访问失败问题排查与许可证诊断
大数据·运维·网络·数据库·人工智能
我是小疯子6640 分钟前
Python变量赋值陷阱:浅拷贝VS深拷贝
java·服务器·数据库
xqhoj1 小时前
Linux——make、makefile
linux·运维·服务器
lifejump1 小时前
Pikachu | XXE
服务器·web安全·网络安全·安全性测试
Zoey的笔记本1 小时前
2026告别僵化工作流:支持自定义字段的看板工具选型与部署指南
大数据·前端·数据库
静听山水1 小时前
docker安装starrocks
数据库
Arwen3032 小时前
IP地址证书的常见问题有哪些?有没有特殊渠道可以申请免费IP证书?
服务器·网络·网络协议·tcp/ip·http·https
学编程的小程2 小时前
从“兼容”到“超越”:金仓KESBSON引擎如何借多模融合改写文档数据库规则
数据库