Javascript 在分析之前更改Meteor.Collection
我有以下问题: 我正在从我的Mongo数据库中检索流星收藏。该集合应通过内置handlebar.js解析为HTML。在此之前,我想更改集合中的值而不将其保存到db,或者向集合中添加新值而不保存它 这是因为插入的数据取决于运行时完成的计算 我尝试了以下几点:Javascript 在分析之前更改Meteor.Collection,javascript,html,mongodb,collections,meteor,Javascript,Html,Mongodb,Collections,Meteor,我有以下问题: 我正在从我的Mongo数据库中检索流星收藏。该集合应通过内置handlebar.js解析为HTML。在此之前,我想更改集合中的值而不将其保存到db,或者向集合中添加新值而不保存它 这是因为插入的数据取决于运行时完成的计算 我尝试了以下几点: var topics = Topic.find({}, {sort: {votes: -1}}); var totalUsers = Meteor.users.find({}).count(); topics.forEach(function
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/Bad/Rest都是0,这是不可能的。在本例中,pctGood/Bad/Rest是我的集合中的存储,其值为0。这就是为什么我假设它在计算后没有改变
我的HTML如下所示:
<div style="width: {{pctGood}}%;">{{pctGood}}%</div>
<div style="width: {{pctRest}}%;">{{pctRest}}%</div>
<div style="width: {{pctBad}}%;">{{pctBad}}%</div>
{{pctGood}}%
{{pctRest}}}%
{{pctBad}}}%
希望任何人都能提供帮助:)找到了一个有效的解决方案。只需在“变换”选项中添加一个函数
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;
}
找到了一个有效的解决方案。只需在“变换”选项中添加一个函数
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;
}
旁注:
numberofgoodvoces
和numberofbaddvoces
应在该匿名函数的范围内。现在它们是全局变量。像var numberOfGoodVoices=…
和var numberOfBadVoices=…
。Thx,编辑此。不幸的是,这并不能解决问题。请注意:numberofgoodvoces
和numberofbaddvoces
应在该匿名函数内进行范围限定。现在它们是全局变量。像var numberOfGoodVoices=…
和var numberOfBadVoices=…
。Thx,编辑此。不幸的是,这并不能解决问题