简体   繁体   English

Firebase Cloudstore集合图与forEach

[英]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. 我正在尝试使用map函数来创建从集合返回的项的数组。

My implementation is using the forEach to iterate which works fine. 我的实现是使用forEach进行迭代,效果很好。 However, I can't get it to work with the map function. 但是,我无法使其与map函数一起使用。

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. 它发出一个错误消息,即“ snap.map”不是一个函数。

I can't figure out where I'm tripping? 我不知道我要去哪里旅行?

The forEach method exists, but not map. forEach方法存在,但不存在映射。

However you can get an array of docs : 但是,您可以获取一系列文档

An array of all the documents in the QuerySnapshot. 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. snap可能不是真正的数组。 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. 那应该将其转换为一个真实的数组,这将使您能够使用.map函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM