变异时,如何解决“ qq模型名称”不是graphql中的构造函数

时间:2019-04-02 11:52:18

标签: mongoose graphql apollo-server

在graphql操场上交换数据时显示 消息:学生不是构造函数 错误:“ TypeError:学生不是构造函数” 学生是我的猫鼬模特。

我尝试重新安装node_modules,在github上搜索一些修复程序。

这是我的变异函数

 addStudent: async (
      root,
      { studentId, firstName, lastName, email, password },
      { Student }
    ) => {
      const newStudent = await new Student({
        studentId,
        firstName,
        lastName,
        email,
        password
      }).save();
      return newStudent;
    }

这是我的猫鼬模型

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const StudentSchema = new Schema({
  studentId: {
    type: String,
    required: true
  },
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  },
  // sectionId: {
  //   type: [Schema.Types.ObjectId],
  //   ref: "Section",
  //   nullable: true
  // },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  createdDate: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model("Student", StudentSchema);

应该创建该学生,但是该消息会弹出该错误。

2 个答案:

答案 0 :(得分:1)

等待兑现承诺,但是您正在传递学生对象 因此它返回Student不是构造函数

const newStudent = await new Student({
        studentId,
        ....
      }).save();

相反,您可以这样做

1)使用append创建学生对象

const newStudent = new Student({})
newStudent.studentId = studentId
newStudent.firstName = firstName
newStudent.lastName = lastName
newStudent.email = email
newStudent.password = password

2)使用构造函数创建学生对象

const newStudent = new Student({ 
    studentId,
    firstName,
    lastName,
    email,
    password
})

并使用promise async和await进行保存

  await newStudent.save()

const newStudent = await Student.create({
    studentId,
    firstName,
    lastName,
    email,
    password
})

答案 1 :(得分:0)

已修复!我应该提供查询变量,而不是在graphql突变上手动输入