node.js Mongoose,CastError:尝试保存包含模型的模型时,Cast to Array 的值失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33383207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongoose, CastError: Cast to Array failed for value when trying to save a model that contains a model
提问by errorreplicating
I am trying to create the model for my mongodb database using mongoose. This is what I am trying to do:
我正在尝试使用 mongoose 为我的 mongodb 数据库创建模型。这就是我想要做的:
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 class1seems to work okay but when I check mongodb, this is displayed:
保存class1似乎工作正常,但是当我检查 mongodb 时,会显示:
{
"_id" : ObjectId("someId"),
"className" : "TEST1234",
"grades" : [ 30, 40, 30 ],
"marks" : [ 72, 88, 63 ],
"__v" : 0
}
What is "__v : 0"?
什么是"__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" `
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?
错误究竟是什么意思?为什么要将任何内容投射到数组?不应该classes: [Class]是一个类型的数组class吗?
回答by Vinicius Lima
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.
这有效。
回答by Aaron Moore
Explicitly defining the type rule on a property called type is allowed and won't throw an error. like this:
允许在名为 type 的属性上显式定义类型规则,并且不会引发错误。像这样:
type: {type: String}
回答by user2709641
Try changing the class definition to :
尝试将类定义更改为:
var classSchema = mongoose.Schema({className: String, marks: [{type: Number}], grades: [{type: Number}]});
var userSchema = mongoose.Schema({email: String, classes: [classSchema] });
var User = mongoose.model('User',userSchema);
This is required since mongoose is not able to parse the object without a related schema. Now when you create a new Schema for the internal class object and refer it in the main userSchema mongoose should be able to parse your object.
这是必需的,因为 mongoose 无法解析没有相关架构的对象。现在,当您为内部类对象创建新的 Schema 并在主 userSchema 中引用它时,mongoose 应该能够解析您的对象。
回答by Furkan Ba?aran
Your model definition is incorrect, you should fix like below.
您的模型定义不正确,您应该像下面那样修复。
// var Schema = mongoose.Schema;
var User = mongoose.model('User',{
email: String,
classes: [ {type: Schema.Types.ObjectID, ref: 'Class'}]
});
var Class1 = new Class({/*yourDataWillBeHere*/})
Class1.save(function(err, classData) {
var User1 = new User({/*YourDataWillBeHere*/})
User1.classes.push(classData._id);
User1.save(function(err, userData) {
//make something with userData object
})
})
Then you can get fetched data using with populate()like this
然后你可以populate()像这样使用获取数据
User
.find()
.populate('classes')
.exec()
回答by Sergio Rodrigues
By default, if you have an object with key 'type' in your schema, mongoose will interpret it as a type declaration.
默认情况下,如果您的架构中有一个键为“type”的对象,mongoose 会将其解释为类型声明。
// Mongoose interprets this as 'loc is a String'
var schema = new Schema({ loc: { type: String, coordinates: [Number] } });
Changing the typeKey:
更改类型键:
var schema = new Schema({
// Mongoose interpets this as 'loc is an object with 2 keys, type and coordinates'
loc: { type: String, coordinates: [Number] },
// Mongoose interprets this as 'name is a String'
name: { $type: String }
}, { typeKey: '$type' }); // A '$type' key means this object is a type declaration
回答by J. Pichardo
Just for Update
只为更新
Now Mongoose supports subdocuments, which are the documented way to nest arrays,
现在 Mongoose 支持子文档,这是嵌套数组的文档化方式,
var arraySchema = new Schema({
property: String
});
var objectSchema = new Schema({
arrays: [arraySchema]
});
Sources
来源
回答by Grégory NEUT
I got a similar issue using mongoose 5.7.0+ using double nested schema.
我在使用双嵌套模式的 mongoose 5.7.0+ 中遇到了类似的问题。
Except it wasn't related to the keyword typebut a mongoose validation bug.
除了它与关键字无关,type而是一个猫鼬验证错误。
https://github.com/Automattic/mongoose/issues/8472
https://github.com/Automattic/mongoose/issues/8472
Temporary workaround: Use Schema.Types.Mixedfor the subschema
临时解决方法:Schema.Types.Mixed用于子模式

