How to iterate over Collection

Hi guys,

I understand we have the _forEach() function, but that’s not exactly what I am looking for. I essentially need to iterate over the collection (it only has 20 items) and depending on some IF statements, append some strings to a variable and return this string variable to the caller, which is in a different file.

So this is what I have:


email_alert_content = calc.generateEmailAlerts('group');
email.sendAlert('group', email_alert_content);


export function generateEmailAlerts(_group) {
  var items = Item.find({group: _group});
  email_alert_content = '';
  _.forEach(items.fetch(), function(item) {
    if (item.previous_percentage == 0 && item.percentage >= minimum_pct_for_alert) {
      email_alert_content += 'There is a group with ' + item.percentage + '% profit. Buy at: ' + buy_exchange + ' and sell at: ' + sell_exchange + ' \r\n';
    } else if (item.previous_percentage > 0 && item.percentage >= minimum_pct_for_alert) {
      if (item.previous_percentage / item.percentage > minimum_pct_for_alert + minimum_variation_pct_to_send_alert) {
        email_alert_content += 'There is a group with ' + item.percentage + '% profit. Buy at: ' + item.buy_exchange + ' and sell at: ' + item.sell_exchange + ' \r\n';

  return email_alert_content;

This is obviously not working as it seems like the return statement is returning before the completion of the forEach.

I am sure I am not dealing well with the callback but I am not sure how to accomplish this.
I just need to iterate over the collection, append to my string and send it back, thats all.

Any help appreciated, thanks

I tried to use the toArray() function as well but it doesn’t seem to be available in MeteorJs, just in MongoDB itself.
If I could transform the result to an Array and iterate over it synchronously, that would be great.

toArray() is called fetch() in Meteor :slight_smile:
You can also do collection.find().forEach(result => ...)
But wait, you’re already using fetch() in your example…?

Your function looks like it should already be synchronous actually.

Looks like you forgot var in front of email_alert_content.

1 Like