1

我仍然試圖學習流星,並想返回一個人的平均分數(根據他們的衆多評分) - 用戶將被評爲4個變量,我想用助手函數返回他們的「記分卡」。流星.helpers函數輸入參數返回一個對象

什麼是最好(最有效)的方式來列出數據庫中的所有用戶(基於特定的過濾器) - 使用幫助函數?

我的收藏(工人):

{ 
    "_id" : ObjectId("58d3dc44353972841db96049"), 
    "name" : "James", 
    "surname" : "Jones", 
    "createdAt" : ISODate("2017-03-23T14:31:32.512Z") 
    ], 
    "Hist" : [ 
     { 
      "itemDate" : "01/2017", 
      "skill" : "", 
      "review" : { 
       "client" : "101" 
      }, 
      "traits" : { 
       "speed" : 3.0, 
       "distance" : 2.0, 
       "reliability" : 3.0, 
       "overall" : 4.0 
      } 
     } 
    ] 
} 

我的模板:

<template name="scoreCard" > 
    <table> 
     <tr> 
      <div class="col s3">Average Speed</div> 
       <div class="progress grey lighten-4"> 
        <div class="determinate" style="width:{{aSpeed this.userId }}%"> 
         <span class="amount">{{aSpeed this.userId}}</span> 
        </div> 
      </div> 
     </tr> 
    </table> 
</template> 

我的助手:

Template.scoreCard.helpers({ 
    userSkills(userId){ 
     return Workers.aggregate(
     {$unwind:"$Hist"}, 
     {$group: { 
       _id:ObjectId(userId), 
       aSpeed: { $avg: "$Hist.traits.speed"}, 
       aDist: { $avg: "$Hist.traits.distance"}, 
       aRel: { $avg: "$Hist.traits.reliability"}, 
       aOver: { $avg: "$Hist.traits.overall"} 
      } 
     }) 
      }, 
     }); 

,你可以在上面看到...我沒有正確地傳遞用戶ID返回每個用戶實際定義的平均值?

回答

1

你並不需要在組密鑰實際ObjectId值傳遞,使用文檔的_id鍵名,並創建一個初始$match管道,將過濾文件的特定參數化ID IE

Template.scoreCard.helpers({ 
    userSkills(userId) { 
     return Workers.aggregate([ 
      { "$match": { "_id": ObjectId(userId) } }, 
      { "$unwind": "$Hist" }, 
      { "$group": { 
       "_id": "$_id", // or _id: null 
       "aSpeed": { "$avg": "$Hist.traits.speed" }, 
       "aDist": { "$avg": "$Hist.traits.distance" }, 
       "aRel": { "$avg": "$Hist.traits.reliability" }, 
       "aOver": { "$avg": "$Hist.traits.overall" } 
      } } 
     ]); 
    } 
}); 

如果你能執行MongoDB 3.4和更高它具有非常實用的新聚合功能,你可以嘗試一下$reduce運營商允許你計算AVER從列表中年齡而不需要$unwind$group,如下你可以做一個單一的管道:

Template.scoreCard.helpers({ 

    sum(key) { 
     return { 
      "$reduce": { 
       "input": "$Hist", 
       "initialValue": 0, 
       "in": { "$add": ["$$value", key] } 
      } 
     } 
    } 

    userSkills(userId) { 
     return Workers.aggregate([ 
      { "$match": { "_id": ObjectId(userId) } }, 
      { "$addFields": { 
       "histSize": { 
        "$cond": [ 
         { "$eq": [ { "$size": "$Hist" }, 0 ] }, 
         1, 
         { "$size": "$Hist" } 
        ] 
       } 
      } }, 
      { "$addFields": { 
       "aSpeed": { "$divide": [sum("$$this.traits.speed"), "$histSize"] }, 
       "aDist": { "$divide": [sum("$$this.traits.distance"), "$histSize"] }, 
       "aRel": { "$divide": [sum("$$this.traits.reliability"), "$histSize"] }, 
       "aOver": { "$divide": [sum("$$this.traits.overall", "$histSize"] } 
      } } 
     ]); 
    } 
});