I'm learning Meteor by following a book, and right now we want to insert()
the userId
of the user that is currently logged in.
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);
}
}
},
However this.userId
was undefined, so the insert()
didnt work as expected. What's missing to get this working?
Somehow it works in the code below (userId
is defined):
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);
}
});
Why is it that on the server-side, this.userId
works but not Meteor.userId()
?
Meteor.publish("Categories", function() {
return lists.find({owner:this.userId}, {fields:{Category:1}});
});
You should use Meteor.userId() everywhere except in the publish function, inside of the publish function only you have to use this.userId.
this.userId is only available on the server. In your methods because of latency compensation the client has access and needs to emulate what the server will do, so if you use this.userId in Meteor.call then the client will fail when it runs them.
The client does not have access to the userId from this.userId, but both client and server (except in publish functions) have access to the current userId through Meteor.userId().
Hope this clarifies it. It took me quite a while to figure this out.
BTW, I know this is a response to an old post, but I had a hard time finding the answer to this, and hopefully this helps someone going through the same thing in the future.
You should use Meteor.userId()
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With