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

  }

});
相关推荐
失散1318 小时前
分布式专题——1.1 Redis单机、主从、哨兵、集群部署
java·数据库·redis·分布式·架构
2301_7795037618 小时前
MySQL集群高可用架构---mysql高可用之组复制 (MGR)
数据库·mysql·架构
Hello.Reader18 小时前
一文通关 Proto3完整语法与工程实践
java·linux·数据库·proto3
Hello.Reader19 小时前
一文吃透 Protobuf “Editions” 模式从概念、语法到迁移与实战
linux·服务器·网络·protobuf·editions
c萱19 小时前
软件测试错题笔记
软件测试·数据库·笔记·测试工具·oracle·测试用例
長琹19 小时前
AES加密算法详细加密步骤代码实现--身份证号码加解密系统
网络·数据库·人工智能·python·密码学
只因在人海中多看了你一眼20 小时前
B.50.10.06-NoSQL数据库与电商应用
数据库·nosql
烟雨归来20 小时前
3 个 ASM 磁盘故障案例,从故障诊断到解决方案
数据库·oracle
时序数据说21 小时前
时序数据库IoTDB的六大实用场景盘点
大数据·数据库·物联网·时序数据库·iotdb
MyFreeIT21 小时前
MySQL Function
数据库·mysql