Is it possible to get all documents in a Firestore Cloud Function?

后端 未结 2 818
温柔的废话
温柔的废话 2020-12-28 22:11

I want to update a value on all documents in a collection using cloud functions as they are dependent on the creation date, but looking through the Cloud Firestore Triggers

相关标签:
2条回答
  • 2020-12-28 22:42

    You'd typically use the Admin SDK for that in your Cloud Functions code. Once you have that, it's a matter of read the collection as usual. Check the node examples in the firebase documentation on reading all documents from a collection:

    const admin = require('firebase-admin');
    
    admin.initializeApp({
        credential: admin.credential.applicationDefault()
    });
    
    var db = admin.firestore();
    
    var citiesRef = db.collection('cities');
    var allCities = citiesRef.get()
        .then(snapshot => {
            snapshot.forEach(doc => {
                console.log(doc.id, '=>', doc.data());
            });
        })
        .catch(err => {
            console.log('Error getting documents', err);
        });
    
    0 讨论(0)
  • 2020-12-28 23:05

    Its possible. if you want to get your document inside array. Without foreach.

    const admin = require('firebase-admin');
    admin.initializeApp({
        credential: admin.credential.applicationDefault()
    });
    
    const docRef = admin.firestore().collection('cities');
    docRef.get()
    .then(snapshot => {
        let arrayR = snapshot.docs.map(doc => {
           return doc.data();
        }); 
        res.json(arrayR);        
    }).catch(function(error){
        console.log("got an error",error);        
    })
    
    0 讨论(0)
提交回复
热议问题