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

前端 未结 5 1566
清酒与你
清酒与你 2020-12-17 15:32

I have a strange problem and cannot figure out what the problem is. The Error-message doesn\'t help.

I\'m sending an "alarm" to the server and want to save

5条回答
  •  时光说笑
    2020-12-17 16:05

    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

提交回复
热议问题