1
votes

I'm new to Ember CLI and I've been trying to push data to hasMany relationship after it has been created, but I'm getting this weird error Uncaught TypeError: Cannot read property 'push' of undefined Everything seems to be fine this.store.createRecord() is working but .findRecord .push .peekRecord is not working.

My controller:

var VideoToAdd = this.store.find('video', this.get('ActiveCanvas'));
console.log(this.get('ActiveCanvas'));
VideoToAdd.get('hotspots').push(newHotspot);

Video Model

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr(),
  file: DS.attr(),
  hotspots: DS.hasMany('hotspot')
});

Hotspot Model:

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr(),
  onVideo: DS.belongsTo('video'),
  toVideo: DS.attr()
});

Please tell me what's going wrong.

1
I think you want VideoToAdd.get('hotspots').addObject(newHotspot), or .addObjects if it's an array of hotspots. You could also use .pushObject and .pushObjects, but using 'add' will check to make sure that the record doesn't already exist in the array, so it's a little bit safer. - Tom Netzband

1 Answers

3
votes

The store's find method is an asynchronous method that returns a promise (actually a promise object). When you call VideoToAdd.get('hotspots') you get undefined because the promise hasn't resolved yet; the data simply isn't there. If you waited until the promise resolved, you would be fine.

this.store.find('video', this.get('ActiveCanvas')).then(function(VideoToAdd) {
    VideoToAdd.get('hotspots').pushObject(newHotspot);
});

And to echo what Tom Netzband said in the comments, you'll want to use an Ember friendly method to add an object to the array. pushObject or addObject should work.