CastError:尝试保存在mongoose时,转换为undefined_method错误失败

时间:2014-12-03 04:53:30

标签: node.js mongodb mongoose

我在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"

当我正在记录时,正在按照预期打印数组中的Objectid,但它在尝试将数据保存到mongoDB时给出了上面的castError。

有人可以帮我解决一下吗?谢谢

1 个答案:

答案 0 :(得分: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

});

这很好用