【问题标题】:Firestore not creating collection with custom doc IDFirestore 未使用自定义文档 ID 创建集合
【发布时间】:2021-12-25 06:07:38
【问题描述】:

所以,过去几天我一直在尝试添加具有自定义文档 ID 的集合大约 2 天,但我没有成功。

我想使用节点创建一个分析集合,但它从未出现在数据库中。这是我的代码:

const onSubmit = async (_values) => {
    setIsLoading(true);
    setError(null);

    const data = { name: '', pdfUrl: '' };
    if (name != '') {
      data['name'] = name;
      if (pdfUrl) {
        data['pdfUrl'] = pdfUrl;
        // alert(JSON.stringify(data));
        let res = await createAnalysis({ name, pdfUrl });
        console.log(res);
        alert(JSON.stringify(res));
        let json = res.then((json) => console.log(json));
        console.log(json);
      } else {
        addToast({
          title: 'No Title created',
          description: 'You must create a title to proceed.',
          type: 'error',
        });
      }
    } else {
      addToast({
        title: 'No pdf selected',
        description: 'You must selected a pdf to proceed.',
        type: 'error',
      });
    }
  };

它应该执行一个名为createAnalysis 的函数。这是函数:

const createAnalysis = async (data: {
name: string;
  pdfUrl: string;
}): Promise<any> => {
  const name = data.name;
  const pdfUrl = data.pdfUrl;
  const id = makeId(name);
  const ownerId = auth.currentUser.uid;
}
  ];
  // alert(JSON.stringify({ id, name, pdfUrl, ownerId, tools }));
  try {
    const analysisRef = await db.collection('analysis');
    const analysisDoc = await analysisRef.doc(id);
    const analysisCreate = await analysisDoc.set({
      id,
      name,
      pdfUrl,
      ownerId,
      tools,
    });
    console.log(analysisCreate);
    // alert(JSON.stringify(analysisCreate));
    return await analysisCreate;
  } catch (error) {
    // alert(JSON.stringify(error));
    console.error(error);
    return error;
  }
};

它甚至没有显示错误,所以我不知道如何解决这个问题。如果有人知道怎么做,请告诉我。

【问题讨论】:

  • 在每条语句前添加await 无济于事。您可以从await db.collection('analysis')await analysisRef.doc(id)return await analysisCreate 中删除await 关键字。
  • @FrankvanPuffelen,不幸的是,它仍然不起作用。

标签: node.js reactjs firebase google-cloud-firestore react-typescript


【解决方案1】:

您真的需要创建自定义 id 还是只需要将 id 放入数据库以供参考?

如果我没记错的话,你可以试试:

try {
    const analysisRef = db.collection('analysis');
    const analysisDoc = analysisRef.doc();
    const analysisCreate = await analysisDoc.set({
      id: analysisDoc.id,
      name,
      pdfUrl,
      ownerId,
      tools,
    });

【讨论】:

  • 我试过了,还是不行。 (仍然没有错误)
  • 发现我的错误!我忘了在提交表单上添加e.preventDefault
猜你喜欢
  • 2019-11-19
  • 1970-01-01
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-27
  • 2020-12-10
相关资源
最近更新 更多