【问题标题】:this.userId is undefined MongoDB property not inserted after submitthis.userId 是未定义的 MongoDB 属性,提交后未插入
【发布时间】:2013-02-17 16:05:34
【问题描述】:

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

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>

所以当插入一个新类别时,应该设置所有者。但它没有。

这是 MongoDB 中的条目:

> db.lists.find()
{ "Category" : "test-admin", "_id" : "EsybjC3SLnNzCBx2t" }

知道我做错了什么吗? (其实我是在关注《Getting Started with Meteor》图书借阅图书馆的例子

编辑似乎:

console.log(this.userId);
undefined

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    换行:

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

    到这个:

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

    【讨论】:

    • 轰隆隆。与本书编写时相比,API 发生了变化吗?那仍然是 -current-logged-in-user 吗?
    • 我不确定,如果上下文是Meteor,使用this 是否可行。帐户框架是最新的(2 个月),这本书是什么时候写的? Meteor.userId() 应该得到登录用户
    • 我现在正在开发一个应用程序,console.log(this.userId) 在活动中为我工作
    • 这个问题可能和这个stackoverflow.com/questions/15137206/…类似
    • 我认为您需要对{{#each lists}} 中的元素使用事件来获取对象的上下文为this。您的事件当前不在每个循环中。我猜这可能是个问题。值得复制。
    【解决方案2】:

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

    应该是这样的:

    function thatRegistersEvents() {
        var self = this;
    
        // ...
    
        registerSomeEvent(function () {
            return self.someThisProperty;
        });
    }
    

    【讨论】:

    • 谢谢,确实 this.userId 似乎是未定义的(+1),但我认为这可能是由于我在 Meteor 中设置帐户/用户的方式存在问题。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 2020-04-06
      • 2020-02-03
      • 2023-03-20
      • 2021-09-04
      相关资源
      最近更新 更多