简体   繁体   中英

Firebase Firestore & Cloud Functions - QuerySnapshot is not returned from Promise.all()

Given the following code:

return admin.firestore()
    .collection("names")
    .get()
    .then(snapshot => {
        var results = [];
        snapshot.docs.forEach(doc => {
            results.push(doc.id);
        })

        var promises = [];
        results.forEach(function(id){
            promises.push(admin.firestore().doc(`players/${id}`).get());
        }); 

        return Promise.all(promises);
    }).then(players => {
        players.forEach(doc => {
            console.log(doc.data().name);
        });
        return players.docs.length; // undefined
    }).catch(error => {
        console.log(error);
    });

Why is it that players is not a QuerySnapshot ? Iterating the players array does work and doc.data().name prints as expected but docs is not a property of players , thus indicating players is not a QuerySnapshot . How to solve this problem?

players is an array of successful results obtained from the array of promises that you passed to Promise.all() . Each element of that array is going to be a DocumentSnapshot object obtained from the promise returned by get() . You're correctly iterating it with forEach to get a hold of each DocumentSnapshot, and you're calling data() on each snapshot to get its raw javascript value. But there are no QuerySnapshot objects in play here, as you haven't actually performed any queries (only single-document gets, which are not really queries).

Bottom line: the code players.docs.length is assuming that the array of promises in players is something that it is not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM