Nyx*_*nyx 4 javascript jquery mongodb node.js 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);
}
}
},
Run Code Online (Sandbox Code Playgroud)
但是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);
}
});
Run Code Online (Sandbox Code Playgroud)
为什么在服务器端,this.userId工作但不是Meteor.userId()?
Meteor.publish("Categories", function() {
return lists.find({owner:this.userId}, {fields:{Category:1}});
});
Run Code Online (Sandbox Code Playgroud)
小智 8
你应该使用Meteor.userId()除了发布函数之外的任何地方,在发布函数内只需要使用this.userId.
this.userId仅在服务器上可用.在您的方法中,由于延迟补偿,客户端具有访问权限并需要模拟服务器将执行的操作,因此如果您在Meteor.call中使用this.userId,则客户端在运行它们时将失败.
客户端无权访问this.userId中的userId,但客户端和服务器(发布函数除外)都可以通过Meteor.userId()访问当前userId.
希望这能澄清它.我花了很长时间来弄明白这一点.
顺便说一句,我知道这是对旧帖子的回应,但我很难找到答案,希望这有助于某人在将来经历同样的事情.
| 归档时间: |
|
| 查看次数: |
3348 次 |
| 最近记录: |