How to retrieve the internal _id of an object in a helper or event?

61 views Asked by At

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 includes the id of the specific post I am going to leave a comment on in the params. 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....how can I still get the ID of the post when it is no longer available in the router params?

So right now my event code is:

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 like template.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

2

There are 2 answers

0
Stephen Woods On

If I'm understanding this correctly, you are changing your route from having a post's ID to having the title field instead. It also looks like you know about #with. Since you helper is named posts, here is some sample code that I think should work:

Template.post.helpers({
    posts() {
        var post = Posts.findOne({title: FlowRouter.getParam('title')});
        if(post) {
            return post;
        }
    }
});

I believe, then, that your event code can stay the same.

6
Nate On

You are missing passing the template variable into the click event:

 "click #submitComment" : function (event, template) { ....

Notice the (event, template). Now within the event, use template.data._id as you suggested.