this.userId 在 Meteor.publish 中返回未定义

this.userId returns undefined inside Meteor.publish

本文关键字:返回 未定义 publish Meteor userId this      更新时间:2023-09-26

在我的一个Meteor.publish()函数中,this.userId的值为 undefined 。我无法调用Meteor.userId()因为它在发布函数中不可用。你现在应该怎么userId

有四种可能性:

  1. 没有用户登录。

  2. 您从服务器调用该方法,因此不会有用户与调用相关联(除非您从另一个函数调用它,该函数将用户绑定到其环境,例如另一个方法或订阅函数)。

  3. 您甚至没有安装基于帐户的软件包(或任何附加组件)。我只是为了完整起见而包括它。

  4. 您正在使用 ES6 中的箭头函数。 Meteor.publish('invoices', function() { return invoices.find({by: this.userId}); });将正常工作,而Meteor.publish('invoices', () => { return invoices.find({by: this.userId}); });将返回一个空游标,因为this将没有userId属性。这是因为箭头函数不绑定自己的thisargumentssupernew.target

如果肯定不是 (2),那么在客户端上调用方法之前立即登录Meteor.userId()会发生什么情况?

FIXED:
import { Meteor } from 'meteor/meteor';
import { Roles } from 'meteor/alanning:roles';
import _ from 'lodash';
import { check } from 'meteor/check';

import Corporations from '../corporations';
Meteor.publish('corporations.list', () => {
  const self = this.Meteor; // <-- see here 
  const userId = self.userId();
  const user = self.user();
  let filters = {};
  if (user) {
    if (!Roles.userIsInRole(userId, ['SuperAdminHolos'])) { // No Está en el Rol SuperAdminHolos
      filters = { adminsEmails: { $in: _.map(user.emails, 'address') } };
    }
    return Corporations.find(filters);
  } else return;
});

你应该改用 Meteor.userId()。