在Meteor.js中,为什么this.userId == undefined?

时间:2013-07-24 00:27:38

标签: javascript jquery node.js mongodb meteor

我正在通过关注一本书来学习Meteor,现在我们想要insert()当前登录用户的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});
            console.log(this.userId);
            Session.set('adding_category',false);
          }
        }
    },

但是this.userId未定义,因此insert()没有按预期工作。让这个工作缺少什么?

不知何故,它适用于下面的代码(userId已定义):

lists.allow({
    insert: function(userId, doc) {
      return adminUser(userId);
    },
    update: function(userId, docs, fields, modifier) {
      return adminUser(userId);
    },
    remove: function(userId, docs) {
      return adminUser(userId);
    }
});

更新

为什么在服务器端,this.userId有效但Meteor.userId()无效?

Meteor.publish("Categories", function() {
    return lists.find({owner:this.userId}, {fields:{Category:1}});
});

5 个答案:

答案 0 :(得分:8)

除了发布函数之外,你应该使用Meteor.userId()除了发布函数之外,只需要使用this.userId。

this.userId仅在服务器上可用。在您的方法中,由于延迟补偿,客户端具有访问权限并需要模拟服务器将执行的操作,因此如果您在Meteor.call中使用this.userId,则客户端在运行它们时将失败。

客户端无权访问this.userId中的userId,但客户端和服务器(发布函数除外)都可以通过Meteor.userId()访问当前的userId。

希望这澄清一下。我花了很长时间来弄明白这一点。

顺便说一句,我知道这是对旧帖子的回应,但我很难找到答案,希望这可以帮助某人在将来经历同样的事情。

答案 1 :(得分:4)

您应该使用Meteor.userId()代替。

答案 2 :(得分:3)

有关更新问题: Meteor.userId只能在方法调用中调用。在发布函数中使用this.userId。

答案 3 :(得分:1)

根据我的经验,仅在服务器method callspublish functions上使用this.userId以避免错误。另一方面,只要涉及客户(anywhere but the publish functions),就使用Meteor.userId()

答案 4 :(得分:0)

this.userId仅在服务器上可用。 Meteor用户node-fibers在运行时您可以访问环境属性。当你使用NPM包时,让我们说Stripe,你想设置一个回调你要使用Meteor.bindEnvironment()。文档对此没有那么多的表达:http://docs.meteor.com/#/full/timers。另请查看此问题:What's going on with Meteor and Fibers/bindEnvironment()?

在服务器上,代码必须在光纤内运行。

在客户端上,您没有在光纤内运行代码,这就是this.userId无法使用的原因。

相关问题