javascript - 如何使用 javascript 删除具有云功能的 Firestore 集合
问题描述
我对 Firestore 完全陌生,我的问题是,我正在使用 Visual Studio 和 JavaScript 来处理我的 Firestore 云功能。
我有两个集合,一个集合包含我发送或接收的最新消息,第二个集合包含您从特定用户发送和接收的所有文档。
我正在尝试使用云函数触发器,当您在设备上删除最新消息时,会调用一个云函数,该函数将删除该消息所引用的整个集合。
我已经能够使用 onDelete 函数,所以当最近的消息被删除时,该函数被调用,我可以获得被删除文档的所有详细信息,
然后我可以获得我想要删除的收藏的路径,我的问题是我不知道如何从此时删除所有文档。我很确定我必须进行批量删除或类似的事情,但这对我来说很新,我已经在这里搜索过,我仍然很困惑任何帮助将不胜感激。
const functions = require("firebase-functions");
const admin = require('firebase-admin');
admin.initializeApp()
exports.onDeletfunctioncalled =
// recentMsg/currentuid/touid/{documentId}' This is the path to the document that is deleted
functions.firestore.document('recentMsg/currentuid/touid/{documentId}').onDelete(async(snap, context) => {
const documentIdToCollection = context.documentId
// this is the path to the collection I want deleted
return await
admin.firestore().collection(`messages/currentuid/${documentIdToCollection}`).get()
//what do i do from here ???
});
解决方案
您可以使用官方文档中的这个片段(选择语言 node.js):
async function deleteCollection(db, collectionPath, batchSize) {
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);
});
}
我还会将此添加到您的云功能中:
if (context.authType === 'ADMIN') {
return null
}
当您从集合中删除文档时,它将避免该函数再次运行。否则每次删除都会触发该功能,并且对于每个已删除的文档都没有必要。
推荐阅读
- angular - Angular router.navigate 不适用于 Material Autocomplete
- python - 可以使用@staticmethod 替换@classmethod 并返回类的实例吗?
- javascript - 编辑列表中的元素时如何防止整个列表重新呈现?
- c# - Unity3d:希望立方体每次都面向控制器
- pytorch - torch.cat 和 torchvision.transforms 的组合导致张量为零
- html - 对齐不同长度的表单输入元素
- if-statement - 为什么编程中有非运算符?
- python - 如何在python中使用带有随机函数生成器的while循环
- text - 如何准备用于 wordcloud2.js 的双向文本
- java - 将覆盆子连接到java serverSocket