【问题标题】:Delete in cloud firestore gives "doc.delete is not a function"Cloud Firestore 中的删除给出“doc.delete 不是函数”
【发布时间】:2021-01-15 14:30:34
【问题描述】:

我想删除一个文档并从中删除一个特定的子集合。我正在使用网络客户端。如何检索子集合中的所有文档并删除它们?这是我现在拥有的:

let id = e.target.parentElement.getAttribute('data-id');
        if (accountType == 'admin') {
        if(confirm("Are you sure you want to delete this event?")) {

        db.collection('campouts').doc(docIdDoc).collection('attending').get().then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
                doc.delete();
            });
        });

        db.collection('campouts').doc(id).delete().then(() => {
        });

当我单击按钮时,我在控制台中收到此错误:

script.js:123 Uncaught (in promise) TypeError: doc.delete is not a function

【问题讨论】:

    标签: javascript google-cloud-firestore


    【解决方案1】:

    代码中的doc 是QueryDocumentSnapshot,它是文档数据的内存快照。要删除文档,您需要一个 DocumentReference,您可以从快照的 ref 属性中获取它。

    所以:

    db.collection('campouts').doc(docIdDoc).collection('attending').get().then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            doc.ref.delete();
        });
    });
    

    对于此类问题,我强烈建议您将参考文档放在手边。您可以从Query.get -> QuerySnapshot -> QueryDocumentSnapshot -> DocumentSnapshot -> ref -> DocumentReference 跟踪线索。

    【讨论】:

      【解决方案2】:

      试试这个我让你的代码使用 async/await 因为承诺链对我来说很乱。

      const mainFunction = async () => {
        const refs = await db
          .collection('campouts')
          .doc(docIdDoc)
          .collection('attending')
          .get()
      
        await Promise.all(
          refs.map(async (doc) => {
            await doc.ref.delete()
          }),
        )
      }
      mainFunction()
      

      【讨论】:

        猜你喜欢
        • 2021-08-30
        • 2018-10-23
        • 2020-08-09
        • 1970-01-01
        • 2021-10-16
        • 1970-01-01
        • 2021-11-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多