CastError:在尝试保存mongoose时投射undefined_method错误失败

我正在尝试在nodejs中的mongoose模式,并最终在以下错误。我已经定义了两个mongoose模式如下

var markSchema = mongoose.Schema({ examName: String, scores : mongoose.Schema.Types.Mixed }); var studentSchema = mongoose.Schema({ studentID: {type : String, unique : true} , marks: [{type : mongoose.Types.ObjectId, ref : 'marks'}] }); mongoose.model('marks',markSchema); mongoose.model('student',studentSchema); 

而我正在使用它在我的路由器中

  var studentBody = { "studentID": "ST12", "marks": [] }; var markz = { "examName": "Series 1", "scores": { "maths": { "score": 48, "total": 50, "teacher": "xxxx" } } }; var marks; marks = new Marks(markz); marks.save(function(err,mark){ if(err){ console.log("Some problem occured while writing the values to the database "+err); } studentBody.marks.push(mark._id); var student = new Student(studentBody); console.log(JSON.stringify(studentBody,null,4)); // This prints as expected with ObjectId student.save(function(err,student){ // CastError happens here if(err){ console.log("Problem occured while writing the values to the database"+err); } else{ var formatted = "Saved to database :: "+JSON.stringify(student,null,4); console.log(formatted); } }); }); 

但我得到的CastError和错误跟踪是

 CastError: Cast to undefined_method failed for value "547e8cddd90f60a210643ddb" at path "marks" 

它正在打印预期与Objectidarrays时,我logging它,但它给上述castError,同时试图将数据保存到mongoDB。

任何人都可以请帮我弄明白吗? 谢谢

这个错误是因为你写了mongoose.Types.ObjectId而不是mongoose.Schema.Types.ObjectId

 var studentSchema = mongoose.Schema({ studentID: {type : String, unique : true} , marks: [{type : mongoose.Schema.Types.ObjectId, ref : 'marks'}]//change }); 

这工作正常