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

  }

});
相关推荐
zjy277778 分钟前
mysql如何选择合适的索引类型_mysql索引设计实战
jvm·数据库·python
笨蛋不要掉眼泪20 分钟前
Mysql架构揭秘:update语句的执行流程
数据库·mysql·架构
万邦科技Lafite27 分钟前
京东item_get接口实战案例:实时商品价格监控全流程解析
java·开发语言·数据库·python·开放api·淘宝开放平台
疯狂成瘾者42 分钟前
服务器的单体和集群
运维·服务器
秋91 小时前
ruoyi项目更换为mysql9.7.0数据库
数据库
Andya_net1 小时前
MySQL | MySQL 8.0 权限管理实践-精确赋予库、表只读等权限
android·数据库·mysql
筑梦之路3 小时前
harbor数据库报错权限异常如何处理——筑梦之路
数据库·harbor
czlczl200209253 小时前
理解 MySQL 行锁:两阶段锁协议与热点更新优化
数据库·mysql
AllData公司负责人3 小时前
通过Postgresql同步到Doris,全视角演示AllData数据中台核心功能效果,涵盖:数据入湖仓,数据同步,数据处理,数据服务,BI可视化驾驶舱
java·大数据·数据库·数据仓库·人工智能·python·postgresql
哆啦A梦15884 小时前
20, Springboot3+vue3实现前台轮播图和详情页的设计
javascript·数据库·spring boot·mybatis·vue3