Search code examples
ember.jsember-dataember-cli

Ember.js: How to get an array of model IDs from a corresponding array of model attributes


For a Tag model that I have in Ember-Data, I have 4 records in my store:

Tags:

id   tag_name
1    Writing
2    Reading-Comprehension
3    Biology
4    Chemistry

In my code I have an array of tag_names, and I want to get a corresponding array of tag IDs. I'm having 2 problems:

  1. My server is being queried even though I have these tags in my store. When I call store.find('tag', {tag_name: tag_name}), I didn't expect to need a call to the server. Here is all the code I'm using to attempt to create an array of IDs.

    var self = this;
    var tagsArray = ["Writing", "Reading-Comprehension", "Chemistry"];
    var tagIdArr = []
    tagsArray.forEach(function(tag_name) {
        return self.store.find('tag', { tag_name: tag_name }).then(function(tag) {
            tagIdArr.pushObject(tag.get('content').get('0').get('id'));
        })
    })
    return tagIdArr;
    
  2. When I console.log the output of the above code gives me an empty array object with length 0. Clicking on the caret next to the empty array shows three key-value pairs with the correct data. But the array is empty. I'm sure there is a simple explanation for this behavior, but I'm not sure why this is. I've used code similar to the above in other places successfully.


Solution

  • Find hits the server, but peek does not.

    var tagsArray = ["Writing", "Reading-Comprehension", "Chemistry"];
    return this.store.peekAll('tag').filter(function(tag){
        return tagsArray.indexOf(tag) !== -1;
      }).mapBy('id');
    

    See: http://emberjs.com/blog/2015/06/18/ember-data-1-13-released.html#toc_reorganized-find-methods