[英]How to delete documents in a collection with the same key value in Firebase Cloud Firestore
[英]How to do a Batch delete Firestore Documents in a Firebase cloud function
我正在使用 firebase 触发器,当删除某个文档时,我可以使用 firebase 云 ZC1C425268E68385D1AB5074C17A94 获取我希望删除的文档集合的路径。 到目前为止,我的 onDelete function 工作非常头痛。
在触发器上,我得到了我需要获取要删除的集合的路径的 id,然后我使用 .get() 从集合中检索文档
然后我使用 forEach 来获取我想要删除的所有文档。
我的问题是我想使用批量删除,因为我已经阅读了这是最好的方法,因为如果您有超过 500 个文档要删除,除非您使用批量删除,否则您可能会遇到错误
所以当我遍历文档时,我使用 batch.delete(document.id),然后在循环之外我调用 batch.commit()
当 function 被触发时,我在终端中收到此消息
⚠ Your function was killed because it raised an unhandled error.
i functions: Beginning execution of "onDeleteTriggers"
> the doc that We need to delete is KLvuLSa1uSsVjaKmVOB5
> ahOh there was an error deleting the documents
i functions: Finished "onDeleteTriggers" in ~1s
我的完整代码如下
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const { firestore } = require("firebase-admin");
admin.initializeApp();
exports.onDeleteTriggers = functions.firestore.document('recentMsg/currentuid/touid/{documentId}').onDelete(async(snap, context) => {
const params = context.params
const db = admin.firestore();
const batch = db.batch()
await admin.firestore().collection(`messages/currentuid/${params.documentId}`)
.get()
.then(snap => {
snap.forEach(document => {
console.log(`the doc that We need to delete is ${document.id}`)
//this takes in the documents i want to delete
batch.delete(document.id);
})
// then commit them
batch.commit();
})
.catch(functionCalledToHandleError)
})
function functionCalledToHandleError() {
console.log('ahOh there was an error deleting the documents')
}
我对 firebase 云功能非常陌生,所以我只是继续我读过的内容,因为我是新手,所以我觉得很难。 任何帮助将不胜感激
尝试使用此 function 删除集合:
async function deleteCollection(db, collectionPath, batchSize = 100) {
const collectionRef = db.collection(collectionPath);
const query = collectionRef.orderBy("__name__").limit(batchSize);
return new Promise((resolve, reject) => {
deleteQueryBatch(db, query, resolve).catch(reject);
});
}
async function deleteQueryBatch(db, query, resolve) {
const snapshot = await query.get();
const batchSize = snapshot.size;
if (batchSize === 0) {
// When there are no documents left, we are done
resolve();
return;
}
// Delete documents in a batch
const batch = db.batch();
snapshot.docs.forEach((doc) => {
batch.delete(doc.ref);
});
await batch.commit();
// Recurse on the next process tick, to avoid
// exploding the stack.
process.nextTick(() => {
deleteQueryBatch(db, query, resolve);
});
}
export { deleteCollection, deleteQueryBatch };
我建议将其存储到一个文件中,以便您可以在需要时在另一个 function 中重复使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.