Meteor cross collection arrays

44 views Asked by At

I am trying to pull an array from a different collection using collection2. I have been able to do this with objects using the following example for users:

 users: {
   type: String,
   label: "Inspector",
   optional: true,
   autoform: {
     firstOption: 'Choose an Inspector',
     options: function() {
       return Meteor.users.find({}, {
         sort: {
           profile: 1,
           firstName: 1
         }
       }).map(function(c) {
         return {
           label: c.profile.firstName + " " + c.profile.lastName,
           value: c._id
         };
       });
     }
   }
 },

I would like to do the same but for an array of objects. Here is what the source data looks like:

{
  "_id": "xDkso4FXHt63K7evG",
  "AboveGroundSections": [{
    "sectionName": "one"
  }, {
    "sectionName": "two"
  }],
  "AboveGroundItems": [{
    "itemSection": "one",
    "itemDescription": "dfgsdfg",
    "itemCode": "dsfgsdg"
  }, {
    "itemSection": "two",
    "itemDescription": "sdfgsdfg",
    "itemCode": "sdfgsdgfsd"
  }]
}

Here is what my function looks like:

  agSection: {
    type: String,
    optional: true,
    autoform: {
      firstOption: 'Select A Section Type',
      options: function() {
        return TemplateData.find({}, {
          sort: {
            AboveGroundSections: 1,
            sectionName: [0]
          }
        }).map(function(c) {
          return {
            label: c.AboveGroundSections.sectionName,
            value: c.AboveGroundSections.sectionName
          }
        });
      }
    }
  },

I know this, it's just not pulling the data for me. I am sure, I am just missing something small. I am trying to pull all objects within the AboveGroundSection array.

1

There are 1 answers

0
Michel Floyd On

Your .map() is iterating over the set of documents but not over the arrays inside each document. Also I don't think your sorting is going to work the way you hope because of the inner nesting.

Try:

agSection: {
  type: String,
  optional: true,
  autoform: {
    firstOption: 'Select A Section Type',
    options() {
      let opt = [];
      TemplateData.find().forEach(c => {
        c.AboveGroundSections.forEach(s => { opt.push(s.sectionName) });
      });
      return opt.sort().map(o => { return { label: o, value: o } });
    }
  }
},

Also if your AboveGroundSections array only has a single key per element then you can simplify:

"AboveGroundSections": [
  { "sectionName": "one" },
  { "sectionName": "two" }
]

To:

 "AboveGroundSections": [
   "one",
   "two" 
 ]