【问题标题】:How to delete a Firestore collection with cloud functions using javascript如何使用 javascript 删除具有云功能的 Firestore 集合
【发布时间】:2021-08-19 14:55:32
【问题描述】:

我是 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 ???

});

【问题讨论】:

    标签: javascript google-cloud-firestore async-await google-cloud-functions


    【解决方案1】:

    可以使用官方documentation的这个sn-ps(选择语言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
        }
    

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

    【讨论】:

      猜你喜欢
      • 2018-12-09
      • 2021-02-13
      • 2021-08-09
      • 2018-04-23
      • 2021-05-13
      • 2019-09-18
      • 1970-01-01
      • 2019-09-08
      • 2021-02-09
      相关资源
      最近更新 更多