Mongoose Schema Error: “Cast to string failed for value” when pushing object to empty array

Mongoose interprets the object in the Schema with key ‘type’ in your schema as type definition for that object.

deviceId: {
  type : String,
  index : {
    unique : true,
    dropDups : true
    }
}

So for this schema mongoose interprets deviceId as a String instead of Object and does not care about all other keys inside deviceId.

SOLUTION:

Add this option object to schema declaration { typeKey: '$type' }

var deviceSchema = new Schema(
{
   deviceId: {
        type : String,
        index : {
            unique : true,
            dropDups : true
        }
    },
    alarms : [ {
        timestamp : Number,
        dateTime : String, //yyyymmddhhss
        difference : Number,
        actionTaken : String, //"send sms"
    } ]
},
{ typeKey: '$type' }
);

By adding this we are asking mongoose to use $type for interpreting the type of a key instead of the default keyword type

Mongoose Docs reference: https://mongoosejs.com/docs/guide.html#typeKey

Leave a Comment