在Meteor.js中,为什么this.userId==未定义

In Meteor.js, Why is this.userId == undefined?

本文关键字:this userId 为什么 未定义 Meteor js      更新时间:2023-09-26

我正在按照一本书学习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}});
});

除了发布函数外,您应该在任何地方使用Meteor.userId(),在发布函数内部,您只需要使用this.userId.

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

客户端无法从this.userId访问userId,但客户端和服务器(发布功能除外)都可以通过Meteor.userId()访问当前userId。

希望这能澄清这一点。我花了很长时间才弄清楚。

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

您应该使用Meteor.userId()

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

根据我的经验,在仅服务器的方法调用和发布函数上使用this.userId可以避免错误。另一方面,无论何时涉及客户端(除了发布函数之外的任何位置),都要使用Meteor.userId()

this.userId仅在服务器上可用。Meteor用户节点在运行时光纤,并且您可以访问环境属性。当你使用NPM包时,比如Stripe,如果你想设置回调,你必须使用Meteor.bindEnvironment()。文档对此没有太多表达:http://docs.meteor.com/#/full/timers。还要检查这个问题:What';Meteor和Fibers/bindEnvironment()怎么了?

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

在客户端上,您没有在光纤中运行代码,这就是this.userId不可用的原因。