【问题标题】:React Native: How can i retrieve a firebase firestore document as an array?React Native:如何将 firebase firestore 文档作为数组检索?
【发布时间】:2020-09-18 23:18:13
【问题描述】:

我有以下代码。将数组作为对象返回如何纠正?

firebase.firestore().collection('users').get().then((querySnapshot)=>{              
        
          let items = Object.values(querySnapshot);
           this.setState({items});
        console.log(items)

});

这是我的数据库

以下出现在控制台中,不友好从中检索数据

  Array [
      No {
        "Ad": Ti {
          "$o": true,
          "Co": false,
          "Do": Array [],
          "Fo": Array [],
          "Mo": [Function anonymous],
          "No": null,
          "So": Promise {
            "_40": 0,
            "_55": Promise {
              "_40": 0,
              "_55": null,
.........

如何在控制台中返回它

Array [
  Object {
    "imageUrl2": "https://firebasestorage.googleapis.com/v0/b/bnv1-16406.appspot.com/o/images%2FTue%20Sep%2001%202020%2020%3A19%3A39%20GMT%2B0300%20(EAT)?alt=media&token=b9d1a38e-26a2-4d93-af2e-aded4747fff1",
    "shopName": "Buule Mohammed",
    "statuz": "seller",
  },
]

【问题讨论】:

  • 你拥有的代码现在发生了什么
  • @TomaszVizaint 我对这个问题做了一些更正

标签: firebase react-native google-cloud-firestore


【解决方案1】:

我会做以下事情:

firebase.firestore().collection('users').get().then((querySnapshot)=>{              
  const objectsArray = [];
  querySnapshot.forEach((user) => {
    objectsArray.push(user.data());
  });
  console.log(objectsArray);
});

【讨论】:

    【解决方案2】:
    For get data from firestore the method is: 
    
         const dbRef = firebase.firestore().collection('users').get();
            const user = dbRef.subscribe(o => {
                      o.forEach(u => {
                         console.log(u.data());
                       }              
                    })
            });
    
    another method is:
    const userRef = this.db.collection('users').valueChanges();
        userRef.subscribe(k => {
          k.forEach(u => {
            console.log(u)
          })
        })
    
    and if you want more data you need create something lik this: 
    
        ngOnInit(): void {
            this.getUser().subscribe(u => {
              console.log(u);
            })
          }
    
    and method: 
    
        getUser = () => {
            return this.db.collection('users').snapshotChanges().pipe(
              map(action => action.map(a => {
                const id = a.payload.doc.id;
                const data = a.payload.doc.data() as User
                return {id, ...data}
              }))
            )
          }
    

    【讨论】:

      猜你喜欢
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 2020-07-22
      • 2018-11-10
      • 1970-01-01
      • 2021-04-08
      相关资源
      最近更新 更多