假设我有一个能够找到集合中所有未结投注的函数:
app.get('/profile/bet-history', function(req, res, next){
var user = req.user;
if(user){
Bet.find({$query : {"username" : user.username, "settled":false, "paired" : true}, $orderby : {_id : -1}})
.then(function(doc){
res.render('profile/bet-history', {bets: doc, user: req.user});
});
}else{
res.redirect('/login');
}
});
我有一个Handlebars模板,可以呈现上述bets
和user
数据:
<tbody>
{{#if bets}}
{{#each bets}}
<tr>
<td>{{date this.createdAt}}</td>
<td>{{this.market}}({{this.bet}})</td>
<td>{{this.stake}}</td>
<td>{{this.odds}}</td>
<td>{{render the potential returns here}}</td>
</tr>
{{/each}}
{{else}}
<tr>
<td>
<p>You have no matched bets. Please come back later.</p>
</td>
</tr>
{{/if}}
</tbody>
我想通过调用一些函数.find()
对calcReturns()
返回的每个单独结果执行快速“潜在回报”计算,该函数接收返回的投注并将投注乘以赔率然后再渲染函数的结果与.find()
调用返回的数据一起,该调用在{{#each}}
部分中呈现。一个关键要求是我想在外部.js文件中使用一个函数,我不想在Mongo数据库中使用另一个字段。
答案 0 :(得分:1)
您可以在从数据库中检索到投注后在本地计算潜在回报。
app.get('/profile/bet-history', function(req, res, next){
var user = req.user;
if(user){
Bet.find({$query : {"username" : user.username, "settled":false, "paired" : true}, $orderby : {_id : -1}})
.then(function(doc){
// Add the potential_returns for our render object here
doc.forEach(function(x) {
// Calculate the potential returns
x.potential_returns = x.bet * x.odds
})
res.render('profile/bet-history', {bets: doc, user: req.user});
});
}else{
res.redirect('/login');
}
});
potential_returns
可以与<tr>
doc
<tbody>
{{#if bets}}
{{#each bets}}
<tr>
<td>{{date this.createdAt}}</td>
<td>{{this.market}}({{this.bet}})</td>
<td>{{this.stake}}</td>
<td>{{this.odds}}</td>
<td>{{this.potential_returns}}</td>
</tr>
{{/each}}
{{else}}
<tr>
<td>
<p>You have no matched bets. Please come back later.</p>
</td>
</tr>
{{/if}}
</tbody>
答案 1 :(得分:1)
扩展jervtub的答案,为了使用外部JS功能,这是最终的解决方案:
获取请求
var updates = require('./update.js');
app.get('/profile/bet-history', function(req, res, next){
var user = req.user;
if(user){
Bet.find({$query : {"username" : user.username, "settled":false, "paired" : true}, $orderby : {_id : -1}})
.then(function(doc){
// Add the potential_returns for our render object here
doc.forEach(function(x) {
updates.calcReturns(x);
})
res.render('profile/bet-history', {bets: doc, user: req.user});
});
}else{
res.redirect('/login');
}
});
Update.js文件
module.exports = {
calcReturns : function(x){
if(x.bet == "Back"){
x.potential_returns = x.stake * x.odds + x.stake;
}else{
x.potential_returns = x.stake * 2;
}
}
};
把手模板
<tbody>
{{#if bets}}
{{#each bets}}
<tr>
<td>{{date this.createdAt}}</td>
<td>{{this.market}}({{this.bet}})</td>
<td>{{this.stake}}</td>
<td>{{this.odds}}</td>
<td>{{this.potential_returns}}</td>
</tr>
{{/each}}
{{else}}
<tr>
<td>
<p>You have no matched bets. Please come back later.</p>
</td>
</tr>
{{/if}}
</tbody>