Creating fields based on what's returned, meteor pub/sub

时间:2016-04-25 08:51:13

标签: mongodb meteor collections publish

Probably a bad title, I don't know how to precisely describe this.

  Template.body.helpers({
    messages: function () {
      return Messages.find({}, {
        sort: {createdAt: -1}
      });
    }
  });

This is the code I have. On the client side, it takes

{{#each messages}}
  <span class="text"> {{messageText}} </span>
{{/each}}

Each message contains "text" and "username".

How would I go about, in the "return Messages" part, modifying what it returns?

So I would do something like

  Template.body.helpers({
    messages: function () {
      Messages.find().forEach(function(thismsg){
        messageText = slugify(thismsg.messageText)
      };
    }
  });

Get messages, modify the fields and then return them. Could I perhaps do this in subscriptions instead? Please help.

1 个答案:

答案 0 :(得分:1)

You can pass your message in the helper and then you can modify the message and pass back to the template like this.

Your template code.

{{#each messages}}
  <span class="text"> {{slugifyMessage text}} </span>
{{/each}}

You helper code.

Template.body.helpers({
    messages: function () {
      return Messages.find({}, {
        sort: {createdAt: -1}
      });
    }
    slugifyMessage: function(messageText){
       return slugify(messageText);
    }
  });

Please make sure your text that I am passing to slugifyMessage will same name as database you mentioned that you have only two field named username and text, So I took text you can replace this with your doc field that you want to modify.