【问题标题】:Does deleting a document from Firebase's Cloud Firestore delete any sub collections in that document?从 Firebase Cloud Firestore 中删除文档是否会删除该文档中的任何子集合?
【发布时间】:2018-08-08 18:03:09
【问题描述】:

这是我当前如何删除文档的示例:

let transactionsRef = db.collection(Globals.GroupsPath).document(Group.instance.getAll().id).collection(Globals.GroupTransactions)
let query = transactionsRef.whereField(Globals.TransactionCreator, isEqualTo: Auth.auth().currentUser!.uid)
query.getDocuments { (snapshot, error) in
   guard error == nil else {
      print(error!.localizedDescription)
      callback(error)
      return
   }

   if let snapshot = snapshot {
      let batch = self.db.batch()
      for doc in snapshot.documents {
         batch.deleteDocument(doc.reference)
      }
      batch.commit()
      callback(nil)
   }
   // TODO: Create an error here and return it.
}

但我注意到,在 Firestore 数据库中执行此操作后,文档显示为灰色,但我仍然可以单击它并查看该文档中的集合及其数据!

在删除父文档之前,我是否需要手动从子集合中删除每个项目,还是只需要一段时间才能完成删除?这是怎么回事?

【问题讨论】:

    标签: firebase swift4 ios11 google-cloud-firestore


    【解决方案1】:

    删除文档不会删除子集合。您确实需要手动删除所有子集合,如文档中的here 所述。您会看到文档不建议从客户端删除子集合,因为有很多方法可能出错。这对客户端来说是劳动密集型的,可能涉及读写权限问题等。您需要使用服务器或无服务器解决方案。因此,例如,这就是使用 Node.js 在服务器端删除子集合的方式:

    function deleteCollection(db, collectionPath, batchSize) {
         var collectionRef = db.collection(collectionPath);
         var query = collectionRef.orderBy('__name__').limit(batchSize);
    
        return new Promise((resolve, reject) => {
            deleteQueryBatch(db, query, batchSize, resolve, reject);
        });
    }
    
    function deleteQueryBatch(db, query, batchSize, resolve, reject) {
    query.get()
        .then((snapshot) => {
            // When there are no documents left, we are done
            if (snapshot.size == 0) {
                return 0;
            }
    
            // Delete documents in a batch
            var batch = db.batch();
            snapshot.docs.forEach((doc) => {
                batch.delete(doc.ref);
            });
    
            return batch.commit().then(() => {
                return snapshot.size;
            });
        }).then((numDeleted) => {
            if (numDeleted === 0) {
                resolve();
                return;
            }
    
            // Recurse on the next process tick, to avoid
            // exploding the stack.
            process.nextTick(() => {
                deleteQueryBatch(db, query, batchSize, resolve, reject);
            });
        })
        .catch(reject);
    }
    

    【讨论】:

    • 感谢您的回复。我会考虑使用 Firebase 函数来做到这一点。
    • @Jen Person,如何删除在 javascript 中包含嵌套子集合的文档? firestore.collection(parentNd).doc(productTitle).delete().then(function() { } 不工作。这是完整的节点,看起来像 firestore.collection(parentNode).doc(productTitle).collection("categoryList").doc().set({}
    猜你喜欢
    • 2018-03-22
    • 2021-10-16
    • 1970-01-01
    • 2021-01-08
    • 2020-02-17
    • 2018-11-01
    • 2021-07-07
    • 2020-12-11
    • 1970-01-01
    相关资源
    最近更新 更多