React Native:如何检索Firebase Firestore文档作为数组?

时间:2020-09-18 23:18:13

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

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

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

});

这是我的数据库 Firebase Firestore Database Snapshot

以下内容会出现在控制台中,因此不方便从中检索数据

  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",
  },
]

2 个答案:

答案 0 :(得分:1)

我将执行以下操作:

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

答案 1 :(得分:0)

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