Javascript 在Meteor.js中,为什么this.userId==未定义?
我正在跟随一本书学习Meteor,现在我们想要Javascript 在Meteor.js中,为什么this.userId==未定义?,javascript,jquery,node.js,mongodb,meteor,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({C
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
已定义):
更新 为什么在服务器端,
this.userId
可以工作,但不能Meteor.userId()
您应该使用Meteor.userId()。更新问题:
Meteor.userId只能在方法调用中调用。在发布函数中使用this.userId。除了在发布函数中,您应该在任何地方使用Meteor.userId(),只有在发布函数中,您才需要使用this.userId 此.userId仅在服务器上可用。在您的方法中,由于延迟补偿,客户端具有访问权限,并且需要模拟服务器将执行的操作,因此如果您在Meteor.call中使用this.userId,则客户端在运行它们时将失败 客户端无权从此.userId访问用户标识,但客户端和服务器(发布函数中除外)都可以通过Meteor.userId()访问当前用户标识 希望这能澄清这一点。我花了很长时间才弄明白这一点
顺便说一句,我知道这是对一篇旧文章的回应,但我很难找到答案,希望这能帮助将来有人经历同样的事情。根据我的经验,仅在服务器上使用
这个.userId
,以避免错误。另一方面,只要涉及到客户端(),就使用Meteor.userId()。此.userId仅在服务器上可用。Meteor用户在运行时,您可以访问环境属性。当您使用NPM包时,比方说Stripe,并且要设置回调,您必须使用Meteor.bindEnvironment()。文档对此没有太多表现力:。请检查此问题:
在服务器上,代码必须在光纤内运行
在客户端上,您没有在光纤中运行代码,这就是为什么this.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);
}
});
Meteor.publish("Categories", function() {
return lists.find({owner:this.userId}, {fields:{Category:1}});
});