1

I want to use observe for one of my collection on the server but I need to get userId, I'm trying to use this.userId and also Meteor.userId() but not working! see the below code for more detail and error message how to resolve it ?

Messages.find({state:"outbox"}).observe({
    added:  (doc) => {
    console.log(" observe ");
        console.log("userId : " + this.userId);  // undefined
        console.log("Meteor.userId(): " + Meteor.userId()); //  "Exception in queued task: Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions."
        //.......
   }
});

thanks for you attention.

Saeed Jalali
  • 416
  • 4
  • 16

1 Answers1

2

Within the observe callbacks, the this keyword does not point to the publication object (it points to the cursor of the related query), so it does not have a userId property.

You can create a closure to make the userId available to the function using

const userId = this.userId;

in the body of the publication itself, and then simply use it in the callback (as userId).

MasterAM
  • 16,283
  • 6
  • 45
  • 66