meteorsimple-schema

Can't update Array of objects


I'm trying to create an array of objects using simple-schema. In this example, a person has a careerHistory object that is filled with individual positions. I can't figure out how to insert and update the array of objects. It just errors. The only way I can get it to work is to be explicit, eg. 'careerHistory.position.1.company'.

I'm using:

Path: mongodb

const ProfileCandidateSchema = new SimpleSchema({
  userId: {
    type: String,
    regEx: SimpleSchema.RegEx.Id
  },
  careerHistory: { type: Array, optional: true },
  'careerHistory.position': { type: Object, optional: true },
  'careerHistory.position.$': { type: Object, optional: true },
  'careerHistory.position.$.company': { type: String, optional: true },
  'careerHistory.position.$.title': { type: String, optional: true }
});

Path: updateForm.js

ProfileCandidate.update(id, { $set: {
    'careerHistory.position.company': this.state['position.company'],
    'careerHistory.position.title': this.state['position.title'],
  }
});

Solution

  • If you want to push object to array do

    ProfileCandidate.update(id, 
      { $push: { careerHistory: { position: {
        'company': this.state['position.company'],
        'title': this.state['position.title'],
      }}}
    });
    

    if you want to update particular object

    ProfileCandidate.update({ _id: id, 'careerHistory.position.company': this.state['position.company'] }, { $set: {
        'careerHistory.position.$.title': this.state['position.title'],
      }
    });
    

    see $ in set