TypeScript报错Mongoose的Document类型不存在findOneAndUpdate属性如何解决
问题根因
findOneAndUpdate是Mongoose提供的模型静态方法,只能通过你定义的Student/Instructor/Admin模型本身调用,不能通过new关键字生成的实例对象调用。你当前代码先新建了模型实例,再用实例调用该方法,属于调用对象错误,触发运行时异常且没有异常捕获逻辑,因此请求一直处于挂起状态无响应。- 你当前是更新已有用户的密码,不需要新建模型实例,这部分逻辑属于冗余操作。
修复方案
直接调用模型的静态方法执行更新即可,参考修正后的代码:
let update; // 建议整个逻辑块包裹try/catch捕获异常,避免请求无响应 try { switch (key) { case "Student": // 第三个参数{new: true}表示返回更新后的文档,可按需选择是否添加 update = await Student.findOneAndUpdate( { username }, { passwordHash }, { new: true } ); break; case "Teacher": update = await Instructor.findOneAndUpdate( { username }, { passwordHash }, { new: true } ); if (!update) { return res.status(401).json({ errMsg: "Not Done brother" }); } break; case "Admin": update = await Admin.findOneAndUpdate( { username }, { passwordHash }, { new: true } ); break; default: console.error("Please Enter the a valid user key"); return res.status(400).json({ errMsg: "无效的用户类型" }); } // 此处添加你的正常返回逻辑 res.json({ data: update }) } catch (err) { console.error("数据库操作失败:", err) res.status(500).json({ errMsg: "服务端错误" }) }
额外优化建议
你提供的Student Schema中存在字段属性拼写错误,部分必填字段用了require而非正确的required,会导致校验规则不生效,建议统一修正:
// 错误写法 firstName: { type: String, require: true } // 修正后写法 firstName: { type: String, required: true }
内容的提问来源于stack exchange,提问作者Amr Shawki
相关产品推荐
相关产品推荐

