Reputation: 1545
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
);
}
});
Upvotes: 0
Views: 37
Reputation: 21364
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, e.g.:
...
].forEach(lead => insertLead(lead, userId));
and change the function to:
const insertLead = (leadEmail, userId) =>
LeadsCollection.insert({
email: leadEmail,
createdAt: new Date(),
userId,
});
Upvotes: 1