尝试创建(插入)包含数组的对象时出现此错误。
如果我删除"停车"包含阵列的字段一切正常! 但有了它,它不起作用,我已经尝试了我能想到的一切,但我仍然不明白是什么导致了这个错误。
显然有一个问题是投射到一个数组,但它已经是一个arry,我不明白。
我插入的示例对象:
{
"uid": "54654654",
"firstName": "loo",
"lastName": "laa",
"to": "ok",
"seat_no": "15",
"date_departure": "2017-12-31T18:30:00.000Z",
"date_return": "2017-12-31T18:30:00.000Z",
"traveller": "svsbsf",
"parking": [
{
"id": 1,
"numberplate": "3554654",
"brand": "bool",
"model": "baa",
"type": 1,
"$$hashKey": "object:26"
}
]
}
这是猫鼬模型
{
uid: String,
firstName: String,
lastName: String,
dob: Date,
phone: String,
address: String,
profession: String,
nationality: String,
bloodgroup: String,
parking: [ {
numberplate: String,
brand: String,
model: String,
type: String
}],
我得到了这个错误:
"errors": {
"parking": {
"message": "Cast to Array failed for value \"[ { numberplate: '', brand: '', model: '', type: '' },\n { numberplate: '', brand: '', model: '', type: '' } ]\" at path \"parking\"",
"name": "CastError",
"stringValue": "\"[ { numberplate: '', brand: '', model: '', type: '' },\n { numberplate: '', brand: '', model: '', type: '' } ]\"",
"kind": "Array",
"value": [
{
"numberplate": "",
"brand": "",
"model": "",
"type": ""
},
{
"numberplate": "",
"brand": "",
"model": "",
"type": ""
}
],
"path": "parking",
"reason": {
"message": "Cast to string failed for value \"{ numberplate: '', brand: '', model: '', type: '' }\" at path \"parking\"",
"name": "CastError",
"stringValue": "\"{ numberplate: '', brand: '', model: '', type: '' }\"",
"kind": "string",
"value": {
"numberplate": "",
"brand": "",
"model": "",
"type": ""
},
"path": "parking"
}
}
},
"_message": "Ticket validation failed",
"message": "Ticket validation failed: parking: Cast to Array failed for value \"[ { numberplate: '', brand: '', model: '', type: '' },\n { numberplate: '', brand: '', model: '', type: '' } ]\" at path \"parking\"",
"name": "ValidationError"
}
答案 0 :(得分:1)
我建议您将数组项定义为单独的架构,然后定义parking
字段,如下所示:
{
uid: String,
firstName: String,
lastName: String,
dob: Date,
phone: String,
address: String,
profession: String,
nationality: String,
bloodgroup: String,
parking: [ArrayItemTypeYouDefined]
}
有关详细信息,请参阅here。
答案 1 :(得分:0)
请注意,当在数组中投射单个项目时出现错误时,Mongoose也可能会引发此错误。
就我而言,我使用的是正确的子方案
nestedSchema = Schema({label:String, count:{type:Number, default:Symbol()});
actualSchema = Schema({ items:[nestedSchema] });
modalOfActual.items.push({label:'hello'});
验证将失败,因为其中的项目未验证!!!!!什么都不会匹配默认值。就我而言,它是使用Symbol的默认值,但是可以是任何东西...