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

我正在通过一本书学习Meteor,现在我们要insert()当前login用户的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()没有按预期工作。 有什么缺less让这个工作?

不知何故,它在下面的代码( 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()来代替。

你应该使用Meteor.userId()除了发布function,除了发布function,只有你必须使用this.userId。

this.userId只在服务器上可用。 在您的方法,因为延迟补偿客户端访问,并需要模拟服务器将做什么,所以如果你在Meteor.call使用this.userId然后客户端将失败,当它运行它们。

客户端不能从this.userId访问userId,但是客户端和服务器(除了发布函数)都可以通过Meteor.userId()访问当前的userId。

希望澄清一下。 我花了一段时间才弄明白这一点。

顺便说一句,我知道这是对一个旧post的回应,但我很难find答案,希望这有助于未来通过同样的事情。

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

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

this.userId只在服务器上可用。 Meteor用户节点 – 光纤运行时,您可以访问环境属性。 当你使用NPM包,比如说Stripe,并且你想要设置一个callback,你必须使用Meteor.bindEnvironment()。 这些文档没有太多的expression: http : //docs.meteor.com/#/full/timers 。 另外检查这个问题: meteor和光纤/ bindEnvironment()发生了什么?

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

在客户端,你不是在一个光纤内运行你的代码,这就是为什么this.userId不可用。