Reputation: 31
I have the following problem: I'm retrieving a Meteor Collection from my Mongo database. This Collection shall be parsed into HTML via built in handlebar.js. Before that I want to either change a value in the Collection without saving it to the db or add a new value to the Collection without saving it.
This is because the inserted data depends on calculations which is done at runtime.
I tried te following:
var topics = Topic.find({}, {sort: {votes: -1}});
var totalUsers = Meteor.users.find({}).count();
topics.forEach(function(topic){
var numberOfGoodVotes = topic.votes.goodVotes.length;
var numberOfBadVotes = topic.votes.badVotes.length;
topic.pctGood = (numberOfGoodVotes*(100/totalUsers));
topic.pctBad = (numberOfBadVotes*(100/totalUsers));
topic.pctRest = 100 - topic.pctGood - topic.pctBad;
});
Unfortunately pctGood/Bad/Rest are all 0 which cannot be possible. In this case pctGood/Bad/Rest are stores in my Collection and have the value 0. This is why I assume it is not changed after computation.
My HTML looks like this:
<div style="width: {{pctGood}}%;">{{pctGood}}%</div>
<div style="width: {{pctRest}}%;">{{pctRest}}%</div>
<div style="width: {{pctBad}}%;">{{pctBad}}%</div>
Hope anyone can help :)
Upvotes: 1
Views: 166
Reputation: 31
Found a working solution. Just add a function to the transform option.
var topics = Topic.find({}, {sort: {votes: -1}, transform: YOURFUNCTIONGOESHERE});
var YOURFUNCTIONGOESHERE = function(topic){
var totalUsers = Meteor.users.find({}).count();
var numberOfGoodVotes = topic.votes.goodVotes.length;
var numberOfBadVotes = topic.votes.badVotes.length;
topic.pctGood = (numberOfGoodVotes*(100/totalUsers));
topic.pctBad = (numberOfBadVotes*(100/totalUsers));
topic.pctRest = 100 - topic.pctGood - topic.pctBad;
return topic;
}
Upvotes: 1