我正在通过以下一本书学习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}});
});发布于 2013-07-24 00:31:45
您应该使用Meteor.userId()代替。
发布于 2015-02-19 16:14:51
除了在发布函数中,您应该在任何地方使用Meteor.userId(),在发布函数的内部只需要使用this.userId。
this.userId仅在服务器上可用。在您的方法中,由于延迟补偿,客户机可以访问,并且需要模拟服务器将做什么,所以如果在this.userId中使用Meteor.call,那么客户机在运行它们时会失败。
客户机不能从userId访问this.userId,但是客户机和服务器(发布函数除外)都可以通过Meteor.userId()访问当前的userId。
希望这能澄清这一点。我花了好长时间才弄明白这件事。
顺便说一句,我知道这是对一个老帖子的回应,但我很难找到答案,希望这能帮助将来经历同样的事情的人。
发布于 2013-12-26 07:45:54
对于更新问题: Meteor.userId只能在方法调用中调用。在发布函数中使用this.userId。
https://stackoverflow.com/questions/17823268
复制相似问题