gpt4 book ai didi

node.js - Actor 错误: Cast to undefined_method error failed while trying to save in mongoose

转载 作者:太空宇宙 更新时间:2023-11-03 23:39:02 25 4
gpt4 key购买 nike

我在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 时,它给出了上述强制转换错误。

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

最佳答案

这个错误是因为你写的是 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

});

这很好用

关于node.js - Actor 错误: Cast to undefined_method error failed while trying to save in mongoose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27263897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com