Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase cloudstore collections map vs. forEach

I am trying to use the map function to create an array of the items returned from a collection.

My implementation is using the forEach to iterate which works fine. However, I can't get it to work with the map function.

Here's the code:

firestore.collection("notes").doc(this.props.id).collection('items').get()
.then((snap) => {
    let items = []
    snap.forEach((doc) => {
        items.push({id:doc.id,text:doc.data().text})
        console.log(`${doc.id} => ${doc.data()}`);
    });
    console.log(items)
});

However, this doesn't work:

firestore.collection("notes").doc(this.props.id).collection('items').get()
.then((snap) => {
    let items = snap.map((doc) => {
        return {id:doc.id, text:doc.data().text}
    })
    console.log(items)
});

It shoots an error that 'snap.map' is not a function.

I can't figure out where I'm tripping?

like image 579
smartexpert Avatar asked Dec 14 '22 16:12

smartexpert


1 Answers

The forEach method exists, but not map.

However you can get an array of docs:

An array of all the documents in the QuerySnapshot.

Which you can call map on, like this:

let items = snap.docs.map(doc => {
    return { id: doc.id, text: doc.data().text }
})
like image 104
Hanuman Avatar answered Dec 22 '22 01:12

Hanuman