【问题标题】:Deletion in FireStore (Latest Snip)FireStore 中的删除(最新截图)
【发布时间】:2022-01-03 12:14:36
【问题描述】:

我有一个数据表 我想在调用 loadCheckOut 之前删除集合中的每个文档。 我怎样才能用最新的 JS 语法做到这一点。 我正在使用 React JS,它从 getDb() 方法初始化 DB,所以像 db.collection() 这样的方法不起作用我想要一个完整的模块解决方案

 const loadCheckout = async (priceId) => {
    //before adding we must delete existing collection
    const docRef_x = collection(db, `customers/${user.uid}/checkout_sessions`);
    const snapshot = await getDocs(docRef_x);
    const x = await deleteDoc(snapshot);

    const docRef = await addDoc(
      collection(db, `customers/${user.uid}/checkout_sessions`),
      {
        price: priceId,
        success_url: window.location.origin,
        cancel_url: window.location.origin,
      }
    );
    const ref = collection(db, `customers/${user.uid}/checkout_sessions`);
    const snap = onSnapshot(
      ref,
      { includeMetadataChanges: true },
      async (doc) => {
        var error = null,
          sessionId = null;
        var first = true;
        doc.forEach((ele) => {
          if (first) {
            error = ele.data().error;
            sessionId = ele.data().sessionId;
            first = false;
          }
        });
        console.log(sessionId);
        if (error) {
          alert(error);
        }
        if (sessionId) {
          const stripe = await loadStripe(stripe_public_key);
          stripe.redirectToCheckout({ sessionId });
        }
      }
    );
  };

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore es6-modules


    【解决方案1】:

    这行不通:

    const snapshot = await getDocs(docRef_x);
    const x = await deleteDoc(snapshot);
    

    deleteDoc 函数需要一个 DocumentReference,而您的 snapshot 是一个 QuerySnapshot。这与语法的变化几乎没有关系,因为snapshot.delete() 在 SDK 的 v8 及更早版本中也不起作用。

    要删除查询快照中的文档,循环遍历结果并一一删除:

    snapshot.forEach((doc) => {
      deleteDoc(doc.ref);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 2020-07-09
      • 2020-04-28
      • 1970-01-01
      • 2019-02-23
      • 1970-01-01
      相关资源
      最近更新 更多