This simple Messaging App is created to demo the following concept. Suppose I would like to display total number of messages I had with other users, by temporary saving the result of findOne() in the helpers function into “this.varName” and retrieve it at the template with {{varName}} as shown below.
I am aware that Reactive-Var package is more powerful except the varName is retrieve with {{instance.varName.get}}, and it required another install of the package. For my simple usage I think my approach is good enough. But is that a bad practice? If it’s not please advice better approach. Thanks.
<template name="chatTemp"> My total Messages with {{#each users}} {{#if notMe}} <br>{{username}}: {{#if hasMessages}} {{totalMessages}} {{/else}} 0 {{/if}} {{/if}} {{/each}} </template>
/* chat.js User document schema : { _id:string, username: string } Chat document schema : { _id:string, user1Id: string, user2Id: string, messages: [string, string,...] } */
Chats = new Meteor.collection('chats'); if (isClient) { Template.chatTemp.helpers({ users: function() { return Meteor.users.find(); }, notMe: function() { return Meteor.userId() !== _id; }, hasMessages: function() { var myId = Meteor.userId(); var otherId = _id; var chat = Chats.findOne({$or: [{user1Id: myId}, {user2Id: otherId}]}); if (chat && chat.hasOwnProperty('messages')) { // *** save result to "this" (i.e. user document), bad practice? this.totalMessages = chat.messages.length; return true; } return false; } }) }