Arrays crossing in the world of meteors

Currently, I am attempting to extract an array from a different collection using collection2. So far, I have managed to accomplish this with objects, as demonstrated in the example below 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
        };
      });
    }
  }
},

Now, I am looking to achieve a similar outcome but for an array of objects. Here is an example of the source data structure:

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

Here is a snippet of what my function currently contains:

  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
          }
        });
      }
    }
  },

Although I understand the concept, I am facing difficulties in fetching the desired data. I am positive that I might be overlooking a minor detail. My goal is to retrieve all objects within the AboveGroundSection array.

Answer №1

Your .map() function is looping through the set of documents, but it is not iterating over the arrays within each document. Additionally, the sorting may not work as expected due to the nested structure.

Consider the following approach:

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

If each element in your AboveGroundSections array contains only one key, you can simplify the data structure like this:

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

To:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a similar alternative to ignoring in webpack or browserify?

My code works perfectly in the browser after ignoring two packages with browserify: browserify files.js -i fs-extra -i request --standalone files > files.browserify.js. However, when I try to use webpack instead, the code throws errors about missing mod ...

What steps should I take if the slackbot is properly functioning after being invited to the channel?

Using an OAuth2 token I am looking to automate the process of sending data from Google Sheets via Slackbot. Even though I have set up tokens and connections, I find that I still need to manually input the channel id into my script. In order to streamline ...

Group users in Mongoose to calculate the total amount for each user

I am utilizing MongoDB and Mongoose as my Object Data Modeling (ODM) tool in next.js, and I am attempting to group by user and aggregate all amounts. Below is the schema I am using: const bonusFillSchema = new mongoose.Schema({ user: { type: S ...

I encountered an error when attempting to integrate Node.js with my terminal in the text editor - permission was denied

After installing node.js and npm, I encountered permission issues when trying to run them from my text editor (VSC). I was advised to open the terminal within the text editor, drag and drop the .js files I'm working on, add "node" and hit "enter" to r ...

Passing array map data to another screen in React Native

Greetings! I successfully created an array map to showcase specific data from my API. Now, I am faced with the challenge of TRANSFERRING THIS DATA TO ANOTHER SCREEN. My current dilemma lies in the fact that the displayed data is generated using ARRAY MAP, ...

Execute functions during jquery's .animate() operation

This is a snippet of code I use to smoothly scroll the browser back to the top: $('html, body').animate({scrollTop: 0}, 500, "easeOutQuart"); Now, I am looking for a way to prevent the user from scrolling while this animation is running. Once t ...

Error: The use of a non-static (JSONPointer) keyId is not permitted in this context

Currently, I am utilizing csfle with mongoDB enterprise 5 while configuring an authenticated client. The field level encryption with json pointer keys is functioning correctly (each document has a unique encryption key). Additionally, I am integrating an ...

Adding array elements to a JavaScript object

I find myself in a rather unique predicament that I'm struggling to navigate. I have come across some data structured as follows. Please bear with me if I use any incorrect terminology, as I am relatively new to this. usersByName: { "tester&q ...

What is the process for making a local storage item accessible to others on a network?

Can a local storage item be accessed from any computer on the network using the same Google Chrome extension that was previously set up? ...

Locate the closing anchor tag following the image

I need to locate the closing anchor tag that wraps an image with the class name "cat-image" in order to move a div right after it. However, I am unable to modify the HTML by adding IDs or classes to the anchor or image tags. Below is an example of the HTM ...

How to incorporate a delay in ng-repeat using AngularJS

Currently, I am facing an issue with my ng-repeat block. In this block, I am generating elements based on data received from an ajax request, which sometimes causes a delay due to latency. Within the same block, I have implemented a filter to remove unwant ...

Creating automatic page additions using Node.js on Heroku?

Can you assist me with a challenge I'm facing? Currently, I am using node.js and heroku to deploy an application and each time I add a new post, I have to manually update my web.js file. This process was manageable when I had fewer pages, but now it&a ...

Tips on how to retrieve a nested promise

Within my JavaScript function, I am utilizing rest calls and the responses to construct the payload for subsequent calls. Included below is some pseudo code exemplifying my approach. Although my code is currently functional, I am unsure how to properly ret ...

Element with adhesive properties alters its color at a particular location

I need the sticky element to change colors at specific points and then revert back to its original color. The color should be orange initially, green on block 2, and orange again on block 3. For the complete code and to address any issues with jQuery, pl ...

passport.authenticate method fails due to empty username and password values

I seem to be making a simple mistake while following a tutorial. Even though I believe I have followed all the steps correctly, when I submit the login form, I get redirected to the "failureRedirect" page. When I checked the source code in the passport mod ...

Issue with React hook state persistence in recursive function

I implemented a recursion custom hook that utilizes a setTimeout function to provide 3 chances for an operation. Once the chances run out, the recursion should stop. However, I encountered an issue where the setTimeout function is not properly decrementin ...

What is the process of declaring internal class variables within class methods in JavaScript?

Here's a query related to React JS. Can I define internal class variables within a method and then use them in other methods? For instance: class Something extends React.Component { state = { value: 'doesnt matter' }; somethin ...

Angular 2: Testing Firebase Add Functionality with Unit Tests

Is there a way to perform a basic unit test in Angular 2 for testing a simple firebase adding item feature? I've opted for typescript over standard JavaScript in my code. This is the piece of code I want to test: export class AppComponent { r ...

Tips on embedding an HTML page within another HTML page by utilizing a custom directive in AngularJS

I am looking to utilize custom directives in order to insert one HTML page into another. How can I achieve this? The custom directive code is as follows: (here is the .js file) fbModule.directive('fbLogin', function(){ return { ...

Show PDF within the browser using ajax technology

I've come across this question multiple times in various forms, but I still can't seem to find a satisfactory answer. When using the mpdf library to generate PDFs, I send some hidden field data to a PHP script via ajax. Below are snippets of the ...