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

  }

});
相关推荐
.生产的驴1 分钟前
SpringBoot 封装统一API返回格式对象 标准化开发 请求封装 统一格式处理
java·数据库·spring boot·后端·spring·eclipse·maven
子非衣3 分钟前
Windows云主机远程连接提示“出现了内部错误”
服务器·windows
AnsenZhu13 分钟前
2025年Redis分片存储性能优化指南
数据库·redis·性能优化·分片
oydcm30 分钟前
MySQL数据库概述
数据库·mysql
oioihoii41 分钟前
C++23中if consteval / if not consteval (P1938R3) 详解
java·数据库·c++23
带娃的IT创业者1 小时前
《AI大模型趣味实战》基于RAG向量数据库的知识库AI问答助手设计与实现
数据库·人工智能
lLinkl1 小时前
项目笔记2:post请求是什么,还有什么请求
服务器·网络协议·http
珹洺1 小时前
Linux操作系统从入门到实战(三)Linux基础指令(上)
linux·运维·服务器
再睡一夏就好1 小时前
Linux常见工具如yum、vim、gcc、gdb的基本使用,以及编译过程和动静态链接的区别
linux·服务器·c语言·c++·笔记
归寻太乙2 小时前
Linux环境变量
linux·运维·服务器