0

I am implementing a Cloud Function where I am executing several queries.

    let rating_subcollection = await admin.firestore().collection("restaurants_collection").doc(vendor_id).collection('ratings').where('uID', '==', userId)
    .get()
    .then(async function (data) {            
        if (data.empty) {
            let restaurants_collection = admin.firestore().collection("restaurants_collection").doc(vendor_id);
            await admin.firestore().runTransaction(async (transaction) => {
                const restDoc = await transaction.get(restaurants_collection);

                // Compute new number of ratings
                const newNumRatings = restDoc.data().noRat + 1;

                // Compute new average rating
                const oldRatingTotal = restDoc.data().rat * restDoc.data().noRat;
                const newAvgRating = (oldRatingTotal + ratingVal) / newNumRatings;

                // Update restaurant info
                transaction.update(restaurants_collection, {
                    rat: newAvgRating,
                    noRat: newNumRatings
                });
            })
        }
    }).catch(error => {
        return "Couldnt update the rating: " + error;
    })

So, as you can see I am only executing the transaction IF data is empty and I have set async in the then() callback. Is this the right way to do?!

showtime
  • 1
  • 1
  • 17
  • 48

1 Answers1

0

I found this example, where is explained on detail how get a collection using an async function, for example if you want to get a collection:

function getValues(collectionName, docName) {
    return db.collection(collectionName).doc(docName).get().then(function (doc) {
        if (doc.exists) return doc.data().text;
        return Promise.reject("No such document");
    }};
}

Or using await it inside an async function in a try/catch block, if you like that better:

async function doSomething() {
    try {
        let text = await getValues('configuration','helpMessage');
        console.log(text);
    } catch {
        console.log("ERROR:" err);
    }
}
Harif Velarde
  • 733
  • 5
  • 10