【问题标题】:this.userId in meteor insert function does not get returned流星插入函数中的 this.userId 未返回
【发布时间】:2020-11-13 04:04:21
【问题描述】:

我有以下代码,当我尝试获取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
    );
  }
});

【问题讨论】:

  • 一个旁注。您应该使用 Meteor.settings 作为种子用户名和默认密码。更好的是省略密码并发送邀请电子邮件。
  • 值得一提的是,现在它只是在开发中,但我会在与真人进行测试之前添加它

标签: javascript mongodb meteor


【解决方案1】:

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,
  });

【讨论】:

  • 第一个用户的id不一样是正常的吗,不同的文档是1,2,3,4,不应该都是同一个用户id,还要更长吗?
  • 这部分到底发生了什么?._id ||我知道这是一个or语句和一个if语句,但在上下文中发生了什么。
  • 是说如果user._id存在返回这个值,或者如果不返回createUservalue?
  • 奇怪的是,当我控制 userId 常量时,我​​得到了正确的 userId,但它正在插入 0,1,2...
  • 哦,我在 insertLead 函数上搞砸了,现在一切正常:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-27
  • 2017-09-05
  • 1970-01-01
  • 2023-04-04
  • 2013-02-17
  • 2015-07-17
  • 1970-01-01
相关资源
最近更新 更多