Tony
Tony

Reputation: 1140

CastError: Cast to undefined_method error failed while trying to save in mongoose

I was trying out mongoose schema in nodejs and ended up in the following error.I have defined two mongoose schema as follows

    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);

And i am using it inside my router as

    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);
                } 

         });

   });

But i am getting the CastError and the error trace is

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

It is printing as expected with the Objectid in the array when i am logging it,But it giving the above castError while trying to save the data to mongoDB.

Could anyone please help me to figure it out ? Thanks

Upvotes: 1

Views: 1151

Answers (1)

kaxi1993
kaxi1993

Reputation: 4700

this error is because you write mongoose.Types.ObjectId instead of mongoose.Schema.Types.ObjectId

var studentSchema = mongoose.Schema({

   studentID: {type : String, unique : true} ,
   marks: [{type : mongoose.Schema.Types.ObjectId, ref : 'marks'}]//change

});

this works fine

Upvotes: 2

Related Questions