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

  }

});
相关推荐
泡沫·3 分钟前
5.MariaDB数据库管理
数据库·mariadb
i***51265 分钟前
【数据库】MySQL的安装与卸载
数据库·mysql·adb
数白18 分钟前
Oracle 数据迁移最佳实践(不使用第三方工具)
数据库·oracle
周杰伦fans28 分钟前
C# 中的**享元工厂**模式
开发语言·数据库·c#
空空kkk42 分钟前
SpringMVC——拦截器
java·数据库·spring·拦截器
J***51681 小时前
MySql中的事务、MySql事务详解、MySql隔离级别
数据库·mysql·adb
SelectDB1 小时前
Apache Doris 中的 Data Trait:性能提速 2 倍的秘密武器
数据库·后端·apache
i***27951 小时前
Spring boot 3.3.1 官方文档 中文
java·数据库·spring boot
TDengine (老段)2 小时前
TDengine 日期函数 DATE 用户手册
大数据·数据库·物联网·时序数据库·iot·tdengine·涛思数据
q***9942 小时前
IPV6公网暴露下的OPENWRT防火墙安全设置(只允许访问局域网中指定服务器指定端口其余拒绝)
服务器·安全·php