Cloud Firestore collection count

后端 未结 17 1528
庸人自扰
庸人自扰 2020-11-22 09:25

Is it possible to count how many items a collection has using the new Firebase database, Cloud Firestore?

If so, how do I do that?

17条回答
  •  一整个雨季
    2020-11-22 09:32

    Took me a while to get this working based on some of the answers above, so I thought I'd share it for others to use. I hope it's useful.

    '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;
    });
    

提交回复
热议问题