[英]how to get the response object from a single query in cloud firestore using nodejs?
[英]How to get the results of a query as an Object from Cloud Firestore?
我在我的ReactJS项目之一中从firebase实时数据库迁移到Cloud firestore。 我对Firestore还是很陌生。
这就是我所需要的。 考虑到我有存储在'Items'集合中的项目详细信息。
在实时数据库中,我只需要执行以下操作即可获取数据并将其存储在状态中:
database.ref('Items').once('value', (snapshot) => {
this.setState({items: snapshot.val()})
})
snapshot.val()
将Items中的所有对象作为包含它们的单个对象返回。 这使我很容易使用Object.keys(this.state.items).map()
将它们呈现在表中
Firestore并非如此。 Firestore返回一个对象,该对象只能通过迭代每个子对象来检索子对象中的数据。
因此,我能想到的最好的方法是:
db.collection('Items').get().then(gotData)
gotData = (snapshot) => {
snapshot.forEach((item) => {
const item = {[item.id]: item.data()}
this.setState(previousState => ({
items : {...previousState.items, ...item}
}))
})
}
上述解决方案的问题在于,状态将被更新的次数等于集合中项的数量。 所以我想知道是否有更好的方法来做到这一点。
几乎在那里,您只想像这样将空对象放在迭代之外...
db.collection('Items').get().then(snap => {
const items = {}
snap.forEach(item => {
items[item.id] = item.data()
})
this.setState({items})
}
或者,您也可以将其映射,我认为这更容易考虑。
db
.collection('Items')
.get()
.then(collection => {
const items = collection.docs.map(item => {[item.id]: item.data()})
this.setState({ items })
})
或者,您可以使用reduce返回包含所有项目的对象。
db
.collection('Items')
.get()
.then((collection) => {
const items = collection.docs.reduce((res, item) => ({...res, [item.id]: item.data()}), {});
this.setState({items})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.