this.userId 在 Meteor.loginWithFacebook 之后未定义

this.userId is undefined after Meteor.loginWithFacebook

我错过了什么?我在 server 文件夹中有这个发布者:

Meteor.publish("myBooks", () => {
    console.log(this.userId);
    return Books.find({
        owner: this.userId
    });
});

this.userId 始终未定义,无论我是否登录。我使用 Meteor.loginWithFacebook 调用(在 client 文件夹中)使用我的个人资料登录。

您正在使用 fat arrow syntax 来定义将 this 绑定到词法作用域的函数,即 gloabal 作用域,或最近的父函数,在 NodeJS 的情况下。由于父作用域中可能没有定义 userId,因此您看到的 this.userIdundefined

使用 function 形式修复代码中的上下文(即 this):

Meteor.publish("myBooks", function () {
    console.log(this.userId);
    return Books.find({
        owner: this.userId
    });
});