首页 > 解决方案 > 如何使用 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 ???

});

标签: javascriptgoogle-cloud-firestoreasync-awaitgoogle-cloud-functions

解决方案


您可以使用官方文档中的这个片段(选择语言 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
    }

当您从集合中删除文档时,它将避免该函数再次运行。否则每次删除都会触发该功能,并且对于每个已删除的文档都没有必要。


推荐阅读