我正在尝试递归删除 Firestore 文档及其子集合,但是当函数遇到包含子集合的嵌套文档时遇到问题。
这是我正在处理的结构:
parentCol/uid/childCol_1/child_Doc1
parentCol/uid/childCol_1/child_Doc1/child_Col2/child_Doc2
我编写了以下递归删除函数,但当它遇到具有子集合的 child_Doc1 时,它似乎停止了,并且没有删除 child_Col2 下的嵌套数据。相反,它只是记录路径,并没有进一步继续。
// parentCol/uid/childCol_1/child_Doc1
// parentCol/uid/childCol_1/child_Doc1/child_Col2/child_Doc2
const deleteDocumentAndCollections = async (path: string): Promise<void> => {
try {
console.log('deletePath:====>', path);
// Get a reference to the initial document
const documentRef = firestore.doc(path);
// List all subcollections under the document to delete
const subcollections = await documentRef.listCollections();
console.log('Subcollections:====>', subcollections);
// Error deleting document and subcollections: Error: Value for argument "documentPath" must point to a document,
// but was parentCol/uid/childCol_1/
// Your path does not contain an even number of components.
// Recursively process and delete each subcollection
for (const subcollection of subcollections) {
try {
// Call the function recursively to delete the subcollection recursively
await deleteDocumentAndCollections(subcollection.path);
} catch (error) {
console.error('Error processing subcollection:', error);
}
}
// Now, delete the document itself
console.log('Deleting document:', documentRef.path);
await documentRef.delete();
console.log('Successfully deleted document:', documentRef.path);
} catch (error) {
console.error('Error deleting document and subcollections:', error);
}
};
您的函数正在将子集合路径传递给自身,而它立即假定它是文档路径。您无法
firestore.doc()
使用子集合路径创建文档引用(使用)。这就是错误消息试图告诉您的内容。您不需要调用
deleteDocumentAndCollections(subcollection.path)
,而是需要第二个函数,该函数采用子集合路径,列出其嵌套文档路径,并调用deleteDocumentAndCollections
每个文档路径。