通过 Cloud Functions 删除整个集合

Lui*_*uiz 4 javascript node.js firebase google-cloud-platform google-cloud-functions

通过在 Cloud Functions 中创建的函数删除集合

\n\n

当删除用户时,我需要删除包含多个文档的整个集合,因此我决定创建一个函数,以便在删除用户时触发该函数。

\n\n

下面是代码。

\n\n

云函数(index.js):

\n\n
  exports.onUserDeleted = functions.auth.user().onDelete((user) => {\n    deleteCollection(admin.firestore(), user.uid, 15);\n  });\n\n  function deleteCollection(db, collectionPath, batchSize) {\n    var collectionRef = db.collection(collectionPath);\n    var query = collectionRef.orderBy(\'__name__\').limit(batchSize);\n\n    return new Promise((resolve, reject) => {\n      deleteQueryBatch(db, query, batchSize, resolve, reject);\n    });\n  }\n\n  function deleteQueryBatch(db, query, batchSize, resolve, reject) {\n    query.get()\n        .then((snapshot) => {\n          // When there are no documents left, we are done\n          if (snapshot.size === 0) {\n            return 0;\n          }\n\n          // Delete documents in a batch\n          var batch = db.batch();\n          snapshot.docs.forEach((doc) => {\n            batch.delete(doc.ref);\n          });\n\n          return batch.commit().then(() => {\n            return snapshot.size;\n          });\n        }).then((numDeleted) => {\n          if (numDeleted === 0) {\n            resolve();\n            return;\n          }\n\n          // Recurse on the next process tick, to avoid\n          // exploding the stack.\n          process.nextTick(() => {\n            deleteQueryBatch(db, query, batchSize, resolve, reject);\n          });\n        })\n        .catch(reject);\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

尝试执行 firebase 部署命令 --only 函数时,会发生以下错误:

\n\n

65:11 警告 箭头函数预期无返回值 一致返回

\n\n

65:18 警告 避免嵌套承诺 承诺/无嵌套

\n\n

69:11 错误 每个 then() 应该返回一个值或抛出 Promise/Always-return

\n\n

\xe2\x9c\x96 3 个问题(1 个错误,2 个警告)

\n\n

我究竟做错了什么?

\n\n

删除用户时如何删除整个集合?

\n\n

如果您能将上面的代码与我应该应用的逻辑一起发布,我将非常感激。

\n

Ren*_*nec 9

执行如下操作:

const db = admin.firestore();

exports.onUserDeleted = functions.auth.user().onDelete((user) => {

    const collectionRef = db.collection(user.uid);

    var promises = [];

    return collectionRef.get()
    .then(qs => {
       qs.forEach(docSnapshot => {
         promises.push(docSnapshot.ref.delete());
       });
       return Promise.all(promises);
    })
    .catch(error => {
        console.log(error);
        return false; 
    });
});
Run Code Online (Sandbox Code Playgroud)

正如您的代码所反映的以及文档中所建议的(请参阅下面的摘录),如果集合非常大,您可以批量删除文档。如果您认为有必要,我可以让您为此调整上面的代码。

如果您有较大的集合,您可能需要小批量删除文档以避免内存不足错误。重复此过程,直到删除整个集合或子集合。 来源:https ://firebase.google.com/docs/firestore/manage-data/delete-data#collections