this.userId 流星插入函数未返回

this.userId in meteor insert function does not get returned

我有以下代码,当我尝试获取 this.userId 时,我似乎无法将值输入到数据库中。它通过 pub sub 在前端工作,不确定如何解决这个问题,如果我使用 Meteor.userId() 我收到一条错误消息,说它不能用于发布函数。

import { Meteor } from "meteor/meteor";
import { Accounts } from "meteor/accounts-base";
import {
  LeadsCollection,
  LeadsBuilderCollection,
} from "/imports/api/LeadsCollection";
import "/imports/api/leadsMethods";
import "/imports/api/leadsPublications";

const insertLead = (leadEmail) =>
  LeadsCollection.insert({
    email: leadEmail,
    createdAt: new Date(),
    userId: this.userId,
  });
const insertLeadBuilderType = (leadsBuilder) =>
  LeadsBuilderCollection.insert({ type: leadsBuilder });

const SEED_USERNAME = "admin";
const SEED_PASSWORD = "admin";

Meteor.startup(() => {
  if (!Accounts.findUserByUsername(SEED_USERNAME)) {
    Accounts.createUser({
      username: SEED_USERNAME,
      password: SEED_PASSWORD,
    });
  }
  if (LeadsCollection.find().count() === 0) {
    [
      "First Lead",
      "Second Lead",
      "Third Lead",
      "Fourth Lead",
      "Fifth Lead",
      "Sixth Lead",
      "Seventh Lead",
    ].forEach(insertLead);
  }
  if (LeadsBuilderCollection.find().count() === 0) {
    ["Showroom Lead", "Phone Call Lead", "Website Lead"].forEach(
      insertLeadBuilderType
    );
  }
});

this.userId 未以任何方式设置,因为此代码在启动时运行,而不是在方法调用或向客户端发布的上下文中运行。因此,您需要明确说明 userId:

const userId = Accounts.findUserByUsername(SEED_USERNAME)?._id ||
    Accounts.createUser({
      username: SEED_USERNAME,
      password: SEED_PASSWORD,
    });

然后您需要将 userId 提供给您的 insertLead 函数,例如:

   ...
    ].forEach(lead => insertLead(lead, userId));

并将函数更改为:

const insertLead = (leadEmail, userId) =>
  LeadsCollection.insert({
    email: leadEmail,
    createdAt: new Date(),
    userId,
  });