javascript - 使用 firebase 函数删除 Firestore 集合

标签 javascript firebase google-cloud-firestore google-cloud-functions

我正在尝试设置一个 firebase 函数,该函数在删除文档时删除该文档的所有子集合。通过阅读文档,我得到了这段代码:

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');



// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });

exports.DeleteColletionFunction = functions.firestore
    .document('exampleCollection/{exampleID}')
    .onDelete((snap, context) => {
        // Get an object representing the document prior to deletion
      // e.g. {'name': 'Marie', 'age': 66}
      const deletedValue = snap.data();
      deleteCollection()


    });



function deleteCollection(db, collectionPath, batchSize) {
    var collectionRef = db.collection(collectionPath);
    var query = collectionRef.orderBy('__name__').limit(batchSize);

    return new Promise((resolve, reject) => {
      deleteQueryBatch(db, query, batchSize, resolve, reject);
    });
  }

  function deleteQueryBatch(db, query, batchSize, resolve, reject) {
    query.get()
        .then((snapshot) => {
          // When there are no documents left, we are done
          if (snapshot.size == 0) {
            return 0;
          }

          // Delete documents in a batch
          var batch = db.batch();
          snapshot.docs.forEach((doc) => {
            batch.delete(doc.ref);
          });

          return batch.commit().then(() => {
            return snapshot.size;
          });
        }).then((numDeleted) => {
          if (numDeleted === 0) {
            resolve();
            return;
          }

          // Recurse on the next process tick, to avoid
          // exploding the stack.
          process.nextTick(() => {
            deleteQueryBatch(db, query, batchSize, resolve, reject);
          });
        })
        .catch(reject);
  }

我以前从未使用过云函数,因此不确定下一步该做什么。我看到为了使用 delete Collection 函数,必须传递数据库、collectionPath 和 batchSize。在这种情况下传递的正确值是什么?

我应该使用这行代码来获取 firestore 数据库吗?

const database = admin.firestore();

从文档中复制此函数时,我也遇到了一些错误:

Expected '===' and instead saw '=='

[eslint] Avoid nesting promises. (promise/no-nesting) (parameter) snapshot: any

[eslint] Each then() should return a value or throw (promise/always-return) (parameter) resolve: any

这是一个屏幕截图,可以看到错误的位置: enter image description here

感谢您的帮助!

更新:
我改变了一些东西(添加了一个 promise ):

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);


// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
//  response.send("Hello from Firebase!");
// });

exports.DeleteColletionFunction = functions.firestore
    .document('exampleCollection/{exampleID}')
    .onDelete((snap, context) => {
        // Get an object representing the document prior to deletion
      // e.g. {'name': 'Marie', 'age': 66}
      const deletedValue = snap.data();
      const exampleID = context.params.exampleID;

      const BATCH_SIZE = 500;

      const database = admin.firestore();

      const commentsRef = database.collection('exampleCollection').doc(exampleID).collection("comments");

      commentsRef.doc('main').delete();

      const exampleRef = database.collection('exampleCollection').doc(exampleID).collection("exampleSubCollection");
      const deleteExamples = deleteCollection(database, exampleRef, BATCH_SIZE)
      return Promise.all([deleteExamples]);

   });



/**
 * Delete a collection, in batches of batchSize. Note that this does
 * not recursively delete subcollections of documents in the collection
 */
function deleteCollection (db, collectionRef, batchSize) {
    var query = collectionRef.orderBy('__name__').limit(batchSize)

    return new Promise(function (resolve, reject) {
      deleteQueryBatch(db, query, batchSize, resolve, reject)
    })
  }

  function deleteQueryBatch (db, query, batchSize, resolve, reject) {
    query.get()
.then((snapshot) => {
        // When there are no documents left, we are done
        if (snapshot.size === 0) {
          return 0
        }

      // Delete documents in a batch
      var batch = db.batch()
      snapshot.docs.forEach(function (doc) {
        batch.delete(doc.ref)
      })

      return batch.commit().then(function () {
        return snapshot.size
      })
    }).then(function (numDeleted) {
      if (numDeleted <= batchSize) {
        resolve()
        return
      }
      else {
      // Recurse on the next process tick, to avoid
      // exploding the stack.
      return process.nextTick(function () {
        deleteQueryBatch(db, query, batchSize, resolve, reject)
      })
    }
  })
    .catch(reject)
  }

现在我在 firebase 控制台中收到错误消息:

ReferenceError: exampleID is not defined at exports.DeleteColletionFunction.functions.firestore.document.onDelete (/user_code/index.js:26:66) at Object. (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27) at next (native) at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71 at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12) at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36) at /var/tmp/worker/worker.js:728:24 at process._tickDomainCallback (internal/process/next_tick.js:135:7)

感谢您的帮助!

最佳答案

改用 admin.initializeApp();

关于javascript - 使用 firebase 函数删除 Firestore 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51108172/

相关文章:

javascript - applescript 尝试填写网络表单时出现预期的行尾错误

firebase - 当我使用Firebase Unity插件在android中实现FaceBook Auth功能时,它崩溃了

firebase - AdMob 插页式广告仅在原生 react 后显示

ios - 如何修复无法获取默认 token 错误?

firebase - 如何使StreamBuilder停止监听事件

java - Firebase Firestore,如何抢夺Collection中最新(新)对象的变化?

javascript - 为什么 new String ('hello' ) === new String ('hello' ) 的计算结果为 False?

javascript - 如何从 graphql 突变返回新记录而不是 null

javascript - 将文件复制到子目录

typescript - 如何使用Typescript从firebase-admin导入FieldValue?