2013-04-14 24 views
1

我遇到以下问题: 我从Mongo数据库检索Meteor Collection。该集合应通过内置的handlebar.js解析为HTML。在此之前,我想要更改Collection中的值而不将其保存到数据库中,或者将新值添加到Collection中而不保存它。在解析之前更改Meteor.Collection

这是因为插入的数据取决于在运行时完成的计算。

我试过TE如下:

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

不幸的是pctGood /坏/剩下的全是0,这可以是不可能的。在这种情况下,pctGood/Bad/Rest是我的Collection中的商店,其值为0.这就是为什么我认为它在计算后没有更改。

我的HTML看起来像这样:

<div style="width: {{pctGood}}%;">{{pctGood}}%</div> 
<div style="width: {{pctRest}}%;">{{pctRest}}%</div> 
<div style="width: {{pctBad}}%;">{{pctBad}}%</div> 

希望有人能帮助:)

+0

备注:'numberOfGoodVotes'和'numberOfBadVotes'应该在该匿名函数内。现在他们是全局变量。它们的范围如'var numberOfGoodVotes = ...'和'var numberOfBadVotes = ...'。 –

+0

Thx,编辑此。不幸的是,这并不能解决问题 – ToBHo

回答

1

找到一个可行的解决方案。只需将一个函数添加到transform选项。

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; 
}