2014-12-03 54 views
1

我在想的NodeJS出貓鼬模式投射到undefined_method錯誤而失敗,並在下面error.I最終定義了兩個貓鼬架構如下CastError:嘗試在貓鼬救

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" 

它正在按照預期的方式打印數組中的Objectid,但它在嘗試將數據保存到mongoDB時給出上述castError。

任何人都可以請幫我弄明白嗎?由於

回答

2

這個錯誤是因爲你寫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 

}); 

這工作得很好

+0

啊這是工作的罰款!謝謝你的幫助。 – Tony 2014-12-03 09:15:00