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 03 Answers
Reset to default 11The 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
版权声明:本文标题:javascript - Firebase cloudstore collections map vs. forEach - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741982997a2408508.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论