Javascript this.userId是未定义的MongoDB属性,提交后未插入

Javascript this.userId是未定义的MongoDB属性,提交后未插入,javascript,mongodb,meteor,Javascript,Mongodb,Meteor,我的客户端文件中有以下事件: Template.categories.events({ ... 'keyup #add-category': function (e,t){ if (e.which === 13) { var catVal = String(e.target.value || ""); if (catVal) { lists.insert({Category:catVal,owner:this.userId

我的客户端文件中有以下事件:

Template.categories.events({
...

  'keyup #add-category': function (e,t){
    if (e.which === 13)
    {
      var catVal = String(e.target.value || "");
      if (catVal)
      {
        lists.insert({Category:catVal,owner:this.userId});
        Session.set('adding_category', false);
      }
    }
  },
  ...
});
这是相关的模板部分:

<template name="categories">
    <div id="categories" class="btn-group">
        {{#if new_cat}}
        <div class="category">
            <input type="text" id="add-category" value="" />
        </div>

        {{else}}
        <div class="category btn btn-inverse" id="btnNewCat">&plus;</div>
        {{/if}} 
        {{#each lists}}
        <div class="category btn {{list_status}}" id="{{_id}}">     
            {{Category}}
        </div>
        {{/each}}
    </div>
</template>
知道我做错了什么吗?(事实上,我正在学习“流星入门”图书借阅图书馆的例子

编辑似乎:

console.log(this.userId);
undefined

可能不是您在该事件中所期望的。您应该进行调试以确认情况是否属实。您可能只是因为
此.userId
未定义。我建议将
分配给变量(称之为“self”或“that”)在该事件处理程序函数之外,但在范围内,
将是您实际想要的。然后,您可以在事件处理程序内引用该变量

应该是这样的:

function thatRegistersEvents() {
    var self = this;

    // ...

    registerSomeEvent(function () {
        return self.someThisProperty;
    });
}
交换此行:

lists.insert({Category:catVal,owner:this.userId});
对于这一点:

lists.insert({Category:catVal,owner:Meteor.userId()});

这是正确的行为。如果您阅读官方Meteor文档以获取对
This.UserId
的引用,则它仅在和中可用。
This.UserId
Meteor.template()中不可用
,这是您在上面的代码示例中完成的,因此必须在模板中使用。

谢谢,确实,似乎this.userId未定义(+1)但我认为这可能是由于我在Meteor中设置帐户/用户的问题造成的。.boom.这是从书的编写时起的API变化吗?这仍然是-当前登录的用户?我不确定,如果上下文是
Meteor
,使用
this
会起作用。帐户框架非常新(2个月),这本书是什么时候写的?
Meteor.userId()
应该获得登录的用户我现在正在使用一个应用程序,
console.log(this.userId)
在事件中对我有效该问题可能与此类似,我想你需要将事件用于
{each list}中的元素
获取对象的上下文为
this
。您的事件当前不在每个循环中。我猜这可能是个问题。值得复制。
lists.insert({Category:catVal,owner:Meteor.userId()});