angular - 如何在 angularfire firestore 中删除整个文档集合

标签 angular google-cloud-firestore angularfire2

我刚刚更改了我的代码如下,它正在运行。可以在 google cloud-firestore 中批量删除。

async deleteMembersOfGroup(clubId: string, groupId: string) {
    //path of the collection
    const path = "club/" + clubId + "/group/" + groupId + "/group-members";

//query snapshot
    const qry: firebase.firestore.QuerySnapshot = await this.afs.collection(path).ref.get();

    const batch = this.afs.firestore.batch();

//looping through docs in the collection to delete docs as a bulk operation
    qry.forEach(doc => {
      console.log('deleting....', doc.id);
      batch.delete(doc.ref);
    });

//finally commit
    batch.commit().then(res => console.log('committed batch.'))
    .catch(err => console.error('error committing batch.', err));
  }

最佳答案

docs说:

Deleting collections from a Web client is not recommended.

因此省略了示例(尽管提供了 Node.js 示例)。

因此,您可以调整 Node.js 代码以在 JavaScript 中工作(尽管 Google 不推荐这样做),或者您可以使用 Google 提供的云函数解决方案(如果您使用的是云函数)。

Delete collection with a Callable Cloud Function

这是直接来自文档的云函数代码:

云函数代码

/**
 * Initiate a recursive delete of documents at a given path.
 * 
 * The calling user must be authenticated and have the custom "admin" attribute
 * set to true on the auth token.
 * 
 * This delete is NOT an atomic operation and it's possible
 * that it may fail after only deleting some documents.
 * 
 * @param {string} data.path the document or collection path to delete.
 */
exports.recursiveDelete = functions
  .runWith({
    timeoutSeconds: 540,
    memory: '2GB'
  })
  .https.onCall(async (data, context) => {
    // Only allow admin users to execute this function.
    if (!(context.auth && context.auth.token && context.auth.token.admin)) {
      throw new functions.https.HttpsError(
        'permission-denied',
        'Must be an administrative user to initiate delete.'
      );
    }

    const path = data.path;
    console.log(
      `User ${context.auth.uid} has requested to delete path ${path}`
    );

    // Run a recursive delete on the given document or collection path.
    // The 'token' must be set in the functions config, and can be generated
    // at the command line by running 'firebase login:ci'.
    await firebase_tools.firestore
      .delete(path, {
        project: process.env.GCLOUD_PROJECT,
        recursive: true,
        force: true,
        token: functions.config().fb.token
      });

    return {
      path: path 
    };
  });

客户端代码

/**
 * Call the 'recursiveDelete' callable function with a path to initiate
 * a server-side delete.
 */
function deleteAtPath(path) {
    var deleteFn = firebase.functions().httpsCallable('recursiveDelete');
    deleteFn({ path: path })
        .then(function(result) {
            logMessage('Delete success: ' + JSON.stringify(result));
        })
        .catch(function(err) {
            logMessage('Delete failed, see console,');
            console.warn(err);
        });
}

一如既往,为什么GCP这么难!

关于angular - 如何在 angularfire firestore 中删除整个文档集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49531458/

相关文章:

node.js - npm 安装 angularfire2 和 firebase 时出错

Angular 2 将值从模板传递到单击按钮时的函数

angular - Angular 2 使用 Shadow DOM 还是虚拟 DOM?

javascript - 另一个 Google Firebase 错误 "Function returned undefined, expected Promise or value"

ios - 在 Swift 中采用 FIRGeoPoint 到 Codable 协议(protocol)

firebase - 如何从 Dart VM/Dart 集成测试访问 Firebase Firestore?

firebase - AngularFIRE 属性 'subscribe' 在类型 'AngularFireList<{}>' 上不存在

css - Angular 6,如何配置 CSS 设置以在所有组件上创建持久的背景色?

css - Angular-gridster2,第一个添加的元素占用所有网格空间,直到刷新页面

angular - 如何使用 AngularFire2 在 Firebase 中更新用户?