Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
876 views
in Technique[技术] by (71.8m points)

node.js - Mongoose, CastError: Cast to Array failed for value when trying to save a model that contains a model

I am trying to create the model for my mongodb database using mongoose. This is what I am trying to do:

var Class = mongoose.model('Class', {className: String, marks: [{type: Number}], grades: [{type: Number}]});
var User = mongoose.model('User', {email: String, classes: [Class] });


//Lets create a new user
var class1 = new Class({className: 'aaa', marks: [72, 88, 63], grades: [30, 40, 30]});
var user1 = new User({email: '[email protected]', classes: [class1]});

Saving class1 seems to work okay but when I check mongodb, this is displayed:

{ 
  "_id" : ObjectId("someId"), 
  "className" : "TEST1234", 
  "grades" : [ 30, 40, 30 ], 
  "marks" : [ 72, 88, 63 ], 
  "__v" : 0 
}

What is "__v : 0"?

Saving the user is not successful at all, this is the following error:

ValidationError: CastError: Cast to Array failed for value "{ marks: [ 72, 88, 63 ], grades: [ 30, 40, 30 ], _id: someId, className: 'TEST1234' }" at path "classes" `

What exactly does the error mean? Why is it casting anything to a array? Shouldn't classes: [Class] be an array of type class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Man, I had a similar issue creating an Schema like this:

QuestionnaireSchema = mongoose.Schema({
    formId: Number,
    name: String,
    questions: [
        {
            type: String,
            title: String,
            alternatives:[{
                label: String,
                value: "Mixed"
            }]
        }
    ]
});

My mistake was that I am using "type" as a field name and this is reserved word in mongoose.

I just change:

type: String,

to

formType: String,

and that works.

see: https://github.com/Automattic/mongoose/issues/1760


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...