利用Firestore Cloud功能进行计数 [英] Count with Firestore Cloud Functions

查看:46
本文介绍了利用Firestore Cloud功能进行计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算具有Firestore云功能的子集合中的文档数.

I like to count the number of documents in a subcollection with firestore cloud functions.

我的数据库如下所示:groups/{groupId}/members/{memberId}

My database looks like that: groups/{groupId}/members/{memberId}

我想计算每个组的成员数(memberId).这意味着每个组可以具有不同数量的成员,并且可以增加或减少灵活性.

I like to count the number of members (memberId) for each group. That means every group can have a different amount of members, and they can increase or decrease flexible.

会对您的想法感到高兴:-).

Would be happy about your ideas :-).

推荐答案

花点时间让它开始工作,所以我想将其分享给其他人使用:

Took me a while to get this working, so thought I'd share it for others to use:

'use strict';

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

exports.countDocumentsChange = functions.firestore.document('library/{categoryId}/documents/{documentId}').onWrite((change, context) => {

    const categoryId = context.params.categoryId;
    const categoryRef = db.collection('library').doc(categoryId)
    let FieldValue = require('firebase-admin').firestore.FieldValue;

    if (!change.before.exists) {

        // new document created : add one to count
        categoryRef.update({numberOfDocs: FieldValue.increment(1)});
        console.log("%s numberOfDocs incremented by 1", categoryId);

    } else if (change.before.exists && change.after.exists) {

        // updating existing document : Do nothing

    } else if (!change.after.exists) {

        // deleting document : subtract one from count
        categoryRef.update({numberOfDocs: FieldValue.increment(-1)});
        console.log("%s numberOfDocs decremented by 1", categoryId);

    }

    return 0;
});

这篇关于利用Firestore Cloud功能进行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆