[英]How to delete a Firestore collection with cloud functions using javascript
我对 Firestore 完全陌生,我的问题是,我正在使用 Visual Studio 和 JavaScript 来处理我的 Firestore 云功能。
我有两个 collections 一个集合包含我发送或接收的最新消息,第二个集合包含您从特定用户发送和接收的所有文档。
我正在尝试使用云 function 触发器,当您在设备上删除最新消息时,将调用云 function 将删除该消息所指的整个集合。
我已经能够使用 onDelete function,所以当最近的消息被删除时,function 被调用,我可以获得被删除文档的所有详细信息,
然后我可以获得我想要删除的收藏的路径,我的问题是我不知道如何从此时删除所有文档。 我很确定我必须进行批量删除或类似的事情,但这对我来说很新,我已经在这里搜索过,我仍然很困惑任何帮助将不胜感激。
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);
});
}
我还会将此添加到您的云 function:
if (context.authType === 'ADMIN') {
return null
}
当您从集合中删除文档时,它将避免 function 再次运行。 否则每次删除都会触发 function 并且对于每个已删除的文档都是不必要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.