簡體   English   中英

解析前更改Meteor.Collection

[英]Changing a Meteor.Collection before parsing

我有以下問題:我正在從Mongo數據庫中檢索一個Meteor Collection。 應通過內置的handlebar.js將這個Collection解析為HTML。 在此之前,我想更改Collection中的值而不將其保存到db或將新值添加到Collection中而不保存它。

這是因為插入的數據取決於在運行時完成的計算。

我嘗試了以下內容:

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存儲在我的Collection中,其值為0。這就是為什么我認為計算后它不會更改的原因。

我的HTML看起來像這樣:

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

希望任何人都可以幫助:)

找到了可行的解決方案。 只需將一個函數添加到轉換選項即可。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM