将项目添加到游标 MeteorJS
Adding an item to a cursor MeteorJS
这是我现在的代码:
Template.home.helpers({
categories: function(){
// Categories is a collection defined earlier
return Categories.find();
},
});
var categories = Categories.find();
/**
categories.append({
name: "All",
icon: "home"
});
*/
return categories;
},
它只是从我正在使用的数据库中返回所有类别。我想做一个聚合类。例如,看到我有 2 个类别:
[
{
name: "Link",
views: 5
},
{
name: "Time",
views: 10,
}]
假设我想要第三类:
{
name: "All",
views: 15 // this is from 10 + 5
}
我该如何将其添加到游标?
除了return一个游标,助手还可以return一个数组(或单个值)。因此,您可以通过将所有现有类别提取到一个数组中,用所需数据修改它,然后 returning 修改后的数组来解决您的问题。这是一个示例实现:
Template.home.helpers({
categories: function() {
// fetch all of the categories into an array
var cats = Categories.find().fetch();
// compute the total views for all categories
var totalViews = _.reduce(cats, function(memo, cat) {
return memo + cat.views;
}, 0);
// add a new 'category' with the total views
cats.push({name: 'All', views: totalViews});
// return the array of modified categories
return cats;
}
});
这是我现在的代码:
Template.home.helpers({
categories: function(){
// Categories is a collection defined earlier
return Categories.find();
},
});
var categories = Categories.find();
/**
categories.append({
name: "All",
icon: "home"
});
*/
return categories;
},
它只是从我正在使用的数据库中返回所有类别。我想做一个聚合类。例如,看到我有 2 个类别:
[
{
name: "Link",
views: 5
},
{
name: "Time",
views: 10,
}]
假设我想要第三类:
{
name: "All",
views: 15 // this is from 10 + 5
}
我该如何将其添加到游标?
除了return一个游标,助手还可以return一个数组(或单个值)。因此,您可以通过将所有现有类别提取到一个数组中,用所需数据修改它,然后 returning 修改后的数组来解决您的问题。这是一个示例实现:
Template.home.helpers({
categories: function() {
// fetch all of the categories into an array
var cats = Categories.find().fetch();
// compute the total views for all categories
var totalViews = _.reduce(cats, function(memo, cat) {
return memo + cat.views;
}, 0);
// add a new 'category' with the total views
cats.push({name: 'All', views: totalViews});
// return the array of modified categories
return cats;
}
});