Search code examples
arraysjsonvalidationmongoosemongoose-schema

Mongoose: ValidationError: materials: Cast to Array failed for value "[ 'glass' ]" at path "materials"


Below is the makerSchema

var makerSchema = new mongoose.Schema({
    materials:[{
        material:{
            type: String,
            required:[true, "Material is a required field"],
            trim:true,
            lowercase:true,
            enum:{
                values:['wood','metal','plastic','glass','concrete','other'], 
                message: 'Please choose from the given options only!'
            }
        }
    }]
},{
    timestamps:true
})
var Maker = mongoose.model('Maker', makerSchema);

I pass the following data through a POST route but get the error

{
    "materials":["glass"]
}

I get the following error

ValidationError: materials: Cast to Array failed for value "[ 'glass' ]" at path "materials"

How do I fix this error and pass the array?


Solution

  • in the maker schema, you defined an array of objects, not an array of strings, so you need to pass an array of objects, each object should be of the form

    { material: 'some string' } 
    

    that's why you got an error

    so you have to pass the materials array as you defined it in the schema like that

    {
        materials: [{
            material: 'glass'
        }]
    }
    

    or change the marker schema to be an array of strings like that

    var makerSchema = new mongoose.Schema({
        materials: [{
            type: String,
            required: [true, "Material is a required field"],
            trim: true,
            lowercase: true,
            enum: {
                values: ['wood', 'metal', 'plastic', 'glass', 'concrete', 'other'],
                message: 'Please choose from the given options only!'
            }
        }]
    }, {
        timestamps: true
    })