Hani Q
Hani Q

Reputation: 155

How to get DocumentReferences in array inside a Document

Very new to await/async pattren in cloud functions. Have a cloud functions that fetches data from a doucment which has an array of DocumentReferences

/* Create  new Chilla for a given date  */
exports.createNewSalikChilla = functions.https.onRequest(async (req, res) => {
    const email=req.body.email;
    const date=req.body.date;

    console.log('Creating chilla for  Salik <' + email + '> on <' + date + '>');

    const db = admin.firestore();
    const habits = [];
    const salikRef = db.collection('saliks').doc(email);
    const salik = await salikRef.get();

    if (!salik.exists) {
        throw new Error("Salik not found for <" + email + ">");
    }

    const assignedHabits = salik.data()['assigned_habits'];

    assignedHabits.forEach(element => { 
       //LOST on how to get these Document Reference and push to habits = []
    });

    res.send({status: "Success"});
});

The document in the saliks collection has the following structure on firestore

assigned_habits<array>:
                        0:
                            habit<reference>: /habits/first
                            required<number>: 200
                        1:
                            habit<reference>: /habits/second
                            required<number>: 4
name: "Hani Q"

But have tried everything and can't seem to figure out how to use async/await here to get all the DocumementReferecnce from the array and push to Habit Array and then after all is done i send back res.send({status: "Success"});

Answer

Below worked after implementing the accepted answer

const assignedHabits = salik.data()['assigned_habits'];
const habits_data = (await Promise.all(assignedHabits.map(element => element.habit.get())))
                    .map(snapshot => snapshot.data());

console.log(habits_data);

res.send({status: habits_data});

Upvotes: 0

Views: 46

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600036

Whenever you need to wait for a bunch of asynchronous operations, you'll want to use Promise.all(). In your case that'd look something like:

const assignedHabits = salik.data()['assigned_habits'];

const habits = await Promise.all(assignedHabits.map(element => element.habit.get()));

res.send({status: "Success"});

The above code assumes that habit is a DocumentReference field type.

Upvotes: 1

Related Questions