【问题标题】:Can write, but can't read Firestore doc可以写入,但无法读取 Firestore 文档
【发布时间】:2022-11-10 22:26:57
【问题描述】:

我想知道,为什么我可以将数据写入 Firestore添加文档并且无法用onSnapshot() 阅读

// CheckoutForm.js

import { addDoc, setDoc, doc, onSnapshot, collection, getDoc } from "firebase/firestore"; 
import { firestore } from "../../firebase";
import { getStripe } from "./initializeStripe";

export async function createCheckoutSession(uid) {
  // Create a new checkout session in the subollection inside this users document

  await addDoc(collection(firestore, "users", `${uid}`, "checkout_sessions"), {
    price: "price_1M0jbXFlIMqx6x27XApjUcnp",
    success_url: window.location.origin,
    cancel_url: window.location.origin,
  })

  // Wait for the CheckoutSession to get attached by the extension
  onSnapshot(doc(firestore, "users", `${uid}`, "checkout_sessions"), (doc) => {
    console.log("Current data: ", doc.data());

    const { sessionId } = doc.data();
    if (sessionId) {
      const stripe = await getStripe();
      stripe.redirectToCheckout({ sessionId });
    }
  });
}

所以这给我一个错误:

未处理的承诺拒绝:FirebaseError:无效的文档参考。文档引用必须有偶数个段,但 users/XQRo8Mn0k7awkxCYPTQ7IeWHID93/checkout_sessions 有 3

在我得到一些相同的东西之前,当尝试使用setDoc 写入数据时,我仍然不明白为什么我不能这样做,现在onSnapshot() 也是如此,需要一些确切数量的路径。 当我使用addDoc 写入数据时,该数据会提供给文档随机ID,因此我无法进入。

我会很高兴得到帮助!

马克西姆

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore


    【解决方案1】:

    正如错误所暗示的,您的文档路径中有 3 个段指向集合而不是文档。在这里,您可以从addDoc 的结果中获取新创建的文档的ID,并在onSnapshot 中使用,如下所示:

    const docRef = await addDoc(collection(firestore, "users", `${uid}`, "checkout_sessions"), {
      price: "price_1M0jbXFlIMqx6x27XApjUcnp",
      success_url: window.location.origin,
      cancel_url: window.location.origin,
    })
    
    // Wait for the CheckoutSession to get attached by the extension
    onSnapshot(doc(firestore, "users", `${uid}`, "checkout_sessions", docRef.id), (doc) => {
      console.log("Current data: ", doc.data());
    
      const {
        sessionId
      } = doc.data();
      if (sessionId) {
        const stripe = await getStripe();
        stripe.redirectToCheckout({
          sessionId
        });
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-17
      • 2021-11-03
      • 2018-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      相关资源
      最近更新 更多