wyc
wyc

Reputation: 55283

Adding an user field to a Meteor record?

Right now, my Posts model has a title and a content field:

client/client.js:

Meteor.subscribe('all-posts');

Template.posts.posts = function () {
  return Posts.find({});
};

Template.posts.events({
  'click input[type="button"]' : function () {
    var title = document.getElementById('title');
    var content = document.getElementById('content');

    if (title.value === '') {
      alert("Title can't be blank");
    } else if (title.value.length < 5 ) {
      alert("Title is too short!");
    } else {
      Posts.insert({
        title: title.value,
        content: content.value,
        author: userId #this show displays the id of the current user
      });

      title.value = '';
      content.value = '';
    }
  }
});

app.html:

      <!--headder and body-->
      <div class="span4">
        {{#if currentUser}}
          <h1>Posts</h1>
          <label for="title">Title</label>
          <input id="title" type="text" />
          <label for="content">Content</label>
          <textarea id="content" name="" rows="10" cols="30"></textarea>

          <div class="form-actions">
            <input type="button" value="Click" class="btn" />
          </div>
        {{/if}}
      </div>

      <div class="span6">
        {{#each posts}}
          <h3>{{title}}</h3>
          <p>{{content}}</p>
          <p>{{author}}</p>
        {{/each}}
      </div>
    </div>
  </div>
</template>

I tried adding an author field (already did meteor add accounts-password and accounts-login):

author: userId

But it just shows the id of the current user who is logged in. I would like it to show the email of the author of the post instead.

How to accomplish that?

Upvotes: 0

Views: 394

Answers (2)

zorlak
zorlak

Reputation: 1404

@danielsvane is correct, but since your Post document's author field stores the _id of the author and not the email address, you'll need a template helper in order for the template to know how to get the email address. Try the following:

// html
...
<div class='span6'>
    {{#each posts}}
        {{> postDetail}}
    {{/each}}
</div>
...

<template name="postDetail">
    <h3>{{title}}</h3>
    <p>{{content}}</p>
    <p>{{authorEmail}}</p>
</template>

// javascript
Template.postDetail.helpers({
    // assuming the `author` field is the one storing the userId of the author
    authorEmail: function() { return Meteor.users.findOne(this.author).emails[0]; }
});

If it's always showing the current user and not the user who is the author of the post, then the problem lies in how you're setting the value of the userId variable in your event handler, which isn't code that you showed in your question.

Upvotes: 0

danielsvane
danielsvane

Reputation: 613

I think you can get the email with

Meteor.users.findOne(userId).emails[0];

Upvotes: 1

Related Questions