如何在帮助程序或事件中检索对象的内部_id

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

本文关键字:对象 内部 id 检索 帮助程序 事件      更新时间:2023-09-26

我正在尝试添加注释,它有一个{postId}字段。目前,我返回帖子 id 以将其添加到评论var id = FlowRouter.getParam('id');集合中,因为我的路由包含我将在参数中发表评论的特定帖子的 ID。现在我想更改路由而不是 myapp.com/posts/:id myapp.com/post/:title,所以我无法再从参数中获取 id......当帖子在路由器参数中不再可用时,我如何仍然获取该帖子的 ID?

所以现在我的事件代码是:

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

记得对于其他应用程序,我使用了类似 template.data._id 的东西,但我无法让它工作

这个问题也是针对我的助手和订阅的,我将始终需要获取模板的特定帖子、评论、视频 ID......但是需要找到一种方法,因为我不希望我所有的路线都包含ID。谢谢

您缺少将模板变量传递到点击事件:

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

请注意(event, template)。现在,在活动中,按照您的建议使用template.data._id

如果我理解正确,您将路线从拥有帖子的 ID 更改为拥有标题字段。 看起来你也知道 #with。 由于您的助手名为 posts ,这里有一些我认为应该可以工作的示例代码:

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

那么,我相信您的事件代码可以保持不变。