H Capello
H Capello

Reputation: 43

Using helper to retrieve subcollections from Users

I have a project where each User can have several Expenses. Expenses are stored in the User document.

For example, a user's document looks like this:

{
"username": "Joe Bloggs",
"expenses": [
{
"title": "bucket of paint",
"price": 9.99
},
{
"title": "large mop",
"price": 5.49
}
]
}

I'm trying to build a helper that outputs each Expense of every User, which would end up like this on the page:

Joe Bloggs | Bucket of paint | 9.99
Joe Bloggs | Large mop | 5.49
Cynthia Smith | Small paintbrush | 3.99

If I were just trying to get a list of users, I'd do something like this:

Template.Expenses.helpers({

  allExpenses(){
  var allUsers = Meteor.users.find().fetch();
  return allUsers;

  }

});

... so now I have the users in an array, how would I loop through each user to output their Expense details?

Many thanks,

Upvotes: 1

Views: 42

Answers (2)

You can directly loop through your users with {{#each}} or {{#each in}}

<template name="Expenses">
    {{#each user in allUsers}}
        {{#each expense in user.expense}}
        <p>{{user.username}} | {{expense.title}} | {{expense.price}}</p>
        {{/each}}
    {{/each}}
</template>

Template.Expenses.helper(){
    allUsers(){
        var allUsers = Meteor.users.find().fetch();
        return allUsers;
    }
}

Upvotes: 1

Ahmed Musallam
Ahmed Musallam

Reputation: 9753

Take a look at this solution, explanation in the comments

users = [{ // assuming you have something like this array
  "username": "Joe Bloggs",
  "expenses": [{
    "title": "bucket of paint",
    "price": 9.99
  }, {
    "title": "large mop",
    "price": 5.49
  }]
}, {
  "username": "Dave Peterson",
  "expenses": [{
    "title": "Small Brush",
    "price": 4.59
  }, {
    "title": "Stud finder",
    "price": 19.99
  }]
}];
var expenses = [];
users.forEach(function(currentUser) { // loop over users
  currentUser.expenses.forEach(function(currentExpense) { // loop over current users expenses
    var newExpense = { // create a new expense with needed properties
      username: currentUser.username,
      title: currentExpense.title,
      price: currentExpense.price
    };
    expenses.push(newExpense); // add new expense to expenses array
  });
});

// print the expenses as needed
expenses.forEach(function(expense){
	console.log([expense.username, expense.title, expense.price].join(" | "))
});

Upvotes: 1

Related Questions