How to retrieve this._id of a post in a helper or event?

HI,

for an example I am trying to add a comment and it has a field of {postId} , currently I return the post id to add it to the comment collection doing var id = FlowRouter.getParam('id'); because my route include the id of the specific post I am going to leave a comment on in the params, but now I want to change the routes instead of myapp.com/posts/:id to myapp.com/post/:title so I can’t get the id from the param anymore…what are other ways to do it?

so right now in my event is something like:

Template.post.events({
  "click #submitComment: function () {
      var commentText = $("#commentfield").val();
     var postId = FlowRouter.getParam('id');` 
     Comments.insert({postId: postId, comment: commentText});
  } 

})

I remember for other apps I used something liketemplate.data._id but I can’t get that to work

this questions is also for my helpers and subscriptions, I will always need to get the specific post , comment, video id of the template…but need to find a way since I don’t want all my routes to include the ids on them.
Thanks

Not sure what your context is, but I’ve done something like this:

{{#each post}}
  <form>
    <input type="text" id="commentfield" />
    <button id="submitComment" data-id="{{_id}}">Submit</button>
  </form>
{{/each}}

and

Template.post.events({
  'click #submitComment': function() {
    var commentText = $('#commentfield').val();
    var postId = e.currentTarget.dataset.id;
    Comments.insert({ postId: postId, comment: commentText });
  }
});

Of course, you need the post context somehow, either with an #each or #with. Depends on your use case.

This still won’t work , I think my problem might be the way I am getting the single post to show?

  Template.postPage.helpers({
              thisPost: function() {

    						    var id = FlowRouter.getParam('id');
                    var post = Posts.findOne({ // Get the selected entry data from the collection with the given id.
                        _id: id,
                    }) || {};
                    return post;

          },
    })

and then on the html I do {{#with thisPost}} {{/with}}…this is how you also do it?

thanks

Sorry, I thought you already had the data working. You can use something like

Posts.findOne({ title: FlowRouter.getParam('title') })

but then you need to ensure a unique index on your titles.

1 Like