使用帮助程序从用户检索子集合

时间:2018-01-01 19:37:17

标签: javascript mongodb meteor meteor-blaze

我有一个项目,每个用户可以有几个费用。费用存储在用户文档中。

例如,用户的文档如下所示:

  

{
“username”:“Joe Bloggs”,“费用”:[
{       “标题”:“油漆桶”,
      “价格”:9.99
},
{
      “标题”:“大拖把”,
      “价格”:5.49
}
]
}

我正在尝试构建一个帮助程序,输出每个用户的每个费用,最终会在页面上显示:

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

如果我只是想获得一个用户列表,我会做这样的事情:

Template.Expenses.helpers({

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

  }

});

...所以现在我有一个数组中的用户,我如何循环每个用户输出他们的费用细节?

非常感谢,

2 个答案:

答案 0 :(得分:1)

看一下这个解决方案,在评论中解释



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(" | "))
});




答案 1 :(得分:1)

您可以使用{{#each}}或{{#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;
    }
}