Mongoose schema error: "Casting a string to a string failed for a value" when an object is clicked on an empty array

I have a strange problem and I can’t understand what the problem is. The error message does not help.

I send an “alarm” to the server and want to save this alarm on my “device”, which already exists in the database.

The alarm object sent to the server is as follows:

{actionTaken: "none", 
dateTime: "20152111191512", 
difference: 4.88, 
timestamp: 1448128894781}

The circuit for the device is as follows:

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

I load the device from the database (deviceId is installed):

Thermometer.findOne({
        deviceId : deviceId
}, function(error, device){ 
   //error handling
   var now = (new Date().getTime());
   var nowDateTime = (new Date()).toISOString().slice(0, 19).replace(/[-T\s:]/g, "");
   var newAlarm = {
       timestamp : now,
       dateTime : nowDateTime, // yyyymmddhhmmss
       difference : diff,
       actionTaken : "none"
   };
   device.alarms.push(newAlarm);  //EXCEPTION !

   //       device.save //doesn't get called
});

As you can see in the commentary, I get Exception / Error when I want to click the "newAlarm" object on the alarm array of my device.

: "[ ]" " "

-:

   kind: "string",
   message: "Cast to string failed for value "[object Object]" at path "alarms"",
   name: "CaseError",
   path: "alarms",
   stack: undefined,
   value: {actionTaken: "none", dateTime: "20152111191512", difference: 4.88, timestamp: 1448128894781}

?

. () . ?

:

"express": "3.2.6",
"express-session":"1.7.6",
"hjs": "*",
"mongoose": "4.0.5",
"nodemailer": "1.4.0"

EDIT: . . .

EDIT 2: lastAlarm

device.lastAlarm = alarm;

.lastAlarm undefined... - . , - ?

+6
5

alarms . .. . , .

var alarmSchema = new Schema({
        timestamp : Number,
        dateTime : String, //yyyymmddhhss
        difference : Number,
        actionTaken : String, //"send sms"

});

var deviceSchema = new Schema({
   deviceId: {
        type : String,
        index : {
            unique : true,
            dropDups : true
        }
    },
    alarms : [alarmSchema]
});
+3
var deviceSchema = new Schema({
 deviceId: {
    type : String,
    index : {
        unique : true,
        dropDups : true
    },
    alarms : {type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Alarm' }]}
});

var alarmSchema = new Schema({
    timestamp : Number,
    dateTime : String, //yyyymmddhhss
    difference : Number,
    actionTaken : String, //"send sms"
});

. , , .

0

, ,

var SchemaObject = require('node-schema-object');

// Create custom basic type 
// Type can be extended with more properties when defined 
var NotEmptyString = {type: String, minLength: 1};

// Create sub-schema for user Company 
var Company = new SchemaObject({
  startDate: Date,
  endDate: Date,
  name: NotEmptyString
});

// Create User schema 
var User = new SchemaObject({
  // Basic user information using custom type 
  firstName: NotEmptyString,
  lastName: NotEmptyString,

  // "NotEmptyString" with only possible values as 'm' or 'f' 
  gender: {type: NotEmptyString, enum: ['m', 'f']},

  // Index with sub-schema 
  company: Company,

  // An array of Objects with an enforced type 
  workHistory: [Company],

  // Create field which reflects other values but can't be directly modified 
  fullName: {type: String, readOnly: true, default: function() {
    return (this.firstName + ' ' + this.lastName).trim();
  }}
});

// Initialize a new instance of the User with a value 
var user = new User({firstName: 'Scott', lastName: 'Hovestadt', gender: 'm'});

// Set company name 
user.company.name = 'My Company';

// The date is automatically typecast from String 
user.company.startDate = 'June 1, 2010';

// Add company to work history 
user.workHistory.push({
  name: 'Old Company',
  startDate: '01/12/2005',
  endDate: '01/20/2010'
});

console.log(user.toObject());

// Prints: 
{ firstName: 'Scott',
  lastName: 'Hovestadt',
  gender: 'm',
  company: 
   { startDate: Tue Jun 01 2010 00:00:00 GMT-0700 (PDT),
     endDate: undefined,
     name: 'My Company' },
  workHistory: 
   [ { startDate: Wed Jan 12 2005 00:00:00 GMT-0800 (PST),
       endDate: Wed Jan 20 2010 00:00:00 GMT-0800 (PST),
       name: 'Old Company' } ],
  fullName: 'Scott Hovestadt' }
0

Mongoose "" .

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

, mongoose deviceId String Object deviceId.

:

{ 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' }
);

When adding this, we ask the mongoose to use the $typedefault keyword instead of the default keyword to interpret the typetype

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

0
source

It may already be too late, but here mongoose assumes that deviceId is not an object and is of type String

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

A SIMPLE SOLUTION:

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

Source: https://habr.com/ru/post/1616878/


All Articles