以下是我目前正在删除文档的示例:
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数据库中,文档显示为灰色,但我仍然可以单击它并查看该文档中的集合及其数据!
在删除父文档之前是否需要手动删除子集合中的每个项目,还是只需要一段时间才能完成删除?这是怎么回事?
答案 0 :(得分:2)
删除文档不会删除子集。您需要手动删除所有子集合,如文档中的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);
}