简体   繁体   中英

this.userId in meteor insert function does not get returned

I have the following code and when I try to grab the this.userId I can't seem to get the value entered into the db. It works on the front end throug pub sub not sure how to solve this and if I use Meteor.userId() I get a error saying it can't be used in publish functions.

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 is not set in any way because this code runs on startup, not in the context of a method call or publication to a client. So you'll need to be explicit about the userId:

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

You then need to give that userId to your insertLead function, eg:

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

and change the function to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM