问题
Mutating data in the graphql playground says the message of Message: Student is not a constructor Error: "TypeError: Student is not a constructor" Student is my Mongoose Model.
I've tried reinstalling my node_modules, searching some fix on the github.
This is my Mutation Function
addStudent: async (
root,
{ studentId, firstName, lastName, email, password },
{ Student }
) => {
const newStudent = await new Student({
studentId,
firstName,
lastName,
email,
password
}).save();
return newStudent;
}
and this is my Mongoose Model
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);
The student should be created, but that error pops up with that message.
回答1:
Await working on promise but here you are passing student object so it returns Student is not a constructor
const newStudent = await new Student({
studentId,
....
}).save();
Instead, you can do this
1) create student object using append
const newStudent = new Student({})
newStudent.studentId = studentId
newStudent.firstName = firstName
newStudent.lastName = lastName
newStudent.email = email
newStudent.password = password
2) Create student object using constructor
const newStudent = new Student({
studentId,
firstName,
lastName,
email,
password
})
and save using promise async and await
await newStudent.save()
or
const newStudent = await Student.create({
studentId,
firstName,
lastName,
email,
password
})
回答2:
Fixed! I should have provided query variables rather than manual typing on the graphql mutation
来源:https://stackoverflow.com/questions/55474130/how-to-fix-the-name-of-the-mongoose-model-is-not-a-constructor-in-graphql-when