【问题标题】:fineOneAndUpdate error with typescript: Property 'findOneAndUpdate' does not exist on type 'Document<any, any>. for mongoose打字稿的fineOneAndUpdate错误:类型'Document <any,any>上不存在属性'findOneAndUpdate'。猫鼬
【发布时间】:2021-09-10 10:44:57
【问题描述】:

我有一个 mongoDB 数据库设置,我正在尝试根据用户名进行排序,然后使用新密码更新 passwordHash 变量。我遇到了打字稿问题,给了我标题中提到的错误。到目前为止,这是我的代码:

let update;

    switch (key) {
      case "Student":
        const newStudent = new Student({
          firstName,
          lastName,
          username,
          passwordHash,
          facultyID,
          admissionYear,
          semester,
          enrolledCoursesId,
        });

        update = await newStudent.findOneAndUpdate(
          { username },
          { passwordHash }
        );
        break;
      case "Teacher":
        const newInstructor = new Instructor({
          username,
          passwordHash,
        });

        update = await newInstructor.findOneAndUpdate(
          { username },
          { passwordHash }
        );
        if (!update) {
          return res.status(401).json({ errMsg: "Not Done brother" });
        }

        break;
      case "Admin":
        const newAdmin = new Admin({
          firstName,
          lastName,
          username,
          passwordHash,
          coursesId,
        });

        update = await newAdmin.findOneAndUpdate(
          { username },
          { passwordHash }
        );
        break;
      default:
        console.error("Please Enter the a valid user key");
    }

以上是用于根据用户名进行更新的代码(switch case 用于区分用户类型的关键变量)

const studentSchema = new mongoose.Schema({
  firstName: { type: String, require: true },
  lastName: { type: String, require: true },
  username: { type: String, required: true, unique: true },
  passwordHash: { type: String, require: true },
  admissionYear: { type: Number, default: 2021 },
  semester: { type: Number, default: 20 },
  enrolledCoursesId: { type: Array, default: [0] },
  facultyID: { type: String, default: "60cc8205111a71a2f67da38e" },
  grades: { type: Array, default: [] },
});

const Student = mongoose.model("student", studentSchema);

export default Student;

以上是我的猫鼬模式。

在使用 Insomnia 进行测试时,请求会一直持续下去,永远不会结束。此外,fineOne() 似乎工作正常,但 fineOneAndUpdate() 给了我上面标题中显示的错误。

提前致谢

【问题讨论】:

  • 您在新文档上调用 findOneAndUpdate 吗?你应该在模型上调用它。像 Student.findOneAndUpdate。理想情况下,您希望在新文档中调用类似 .save() 的内容。
  • 嘿@TusharShahi 非常感谢。您的建议有效,现在该功能运行良好。非常感谢

标签: javascript node.js typescript mongodb mongoose


【解决方案1】:

感谢@Tushar Shahi,我意识到我正在制作一个新的空模型,然后尝试访问它而不是访问我当前建立的模型。非常感谢@Tushar Shahi

【讨论】:

    猜你喜欢
    • 2021-05-09
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 2022-12-17
    • 2021-02-08
    相关资源
    最近更新 更多