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.

1
  • Is this being called from within a publish function, or just globally when the server starts? Commented May 15, 2016 at 18:22

1 Answer 1

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.