admin管理员组

文章数量:1315777

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)
});

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?

Share Improve this question asked Jun 5, 2018 at 21:04 smartexpertsmartexpert 3,0653 gold badges27 silver badges43 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 11

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 }
})

snap may not be a true array. It's probably some sort of array-like object. Try creating a new array with the spread operator (...), then working on that, like this:

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)
});

That should convert it to a true array which will give you the ability to use the .map function.

A little example, in my case, Im update something:

const query = ...collection("notes").doc(this.props.id).collection('items');

query.snapshotChanges().map(changes => {
     changes.map(a => {
     const id = a.payload.doc.id;
     this.db.collection("notes").doc(this.props.id).collection('items').update({
            someItemsProp: newValue,
                })
            })
        }).subscribe();
    }

本文标签: javascriptFirebase cloudstore collections map vs forEachStack Overflow