Reputation: 3055
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?
Upvotes: 4
Views: 1832
Reputation: 6017
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();
}
Upvotes: 0
Reputation: 7067
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 }
})
Upvotes: 11
Reputation: 2024
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.
Upvotes: 1