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

前端 未结 5 1605
清酒与你
清酒与你 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 15:54

    Use inner schema to solve this,

    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's 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' }
    

提交回复
热议问题