How can I get data from multiple fireStore collections in React native?

Viewed 182

I have these Collections:

  • User(Uid = document) with name and image,
  • Post(Uid Post = doucment) includes body, image and Uid (Uid user)

I am using nested loops to have a simple object (I do not use 2 arrays)

firebase.firestore().collection("Post").get()
            .then(querySnapshot => {
               querySnapshot.forEach(documentSnapshot => {
                    this.setState({
                        dataPost: this.state.dataPost.concat({
                            ...documentSnapshot.data(),
                            key: documentSnapshot.id,
                            name: this.getUserbyUid(documentSnapshot.data().uid) <- get Name user as soon as I get the uid from the Post collection
                        }),
                    })
              });
      });
  getUserbyUid = (Uid) => {
            firebase.firestore().collection('user').doc(Uid).get()
            .then(documentSnapshot => {
                return documentSnapshot.data().name
            })}

I get an error name: Undefinded

This is the way I think, I know there are many better ways please help me tks

Post

enter image description here

User

enter image description here

Object {
  "body": "hfdbdb"
  "date": 1614903953253,
  "image": “"https://firebasestorage.googleapis.com/v0/t.....-44¢5-b091-7af310de36d1",
  "key": "IX9KKfcOONSyquUtossTd",
  "name": undefined,
  "uid": "Chc1P3zcWMguc2d2ppKSRrpQx752",
},

Object

1 Answers

You need to review your data structure first because as your database grows, looping and extracting data can become very complex.

You can read more about the different data structures here. Each has a different set of pros and cons, and choosing one will depend on your use case.

Once you have a good database foundation, your code will become cleaner and easier to read.

As an example in Python:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore


cred = credentials.ApplicationDefault()

firebase_admin.initialize_app(cred, {
    'projectId': 'test-project',
})

db = firestore.client()

Get User Data

users = db.collection('User').document('document')

user = users.get()

print(f'Data: {user.to_dict()}')

. . .

Data: {'avatar': 'http://my-avatar-image.com',
       'name': 'My Good Name'}

Get Post Data

posts = db.collection('Post').document('document')

post = posts.get()
 
print(f'Data: {post.to_dict()}')

. . .

Data: {'date': '121445475589',
       'body': 'sdfsdfsdf',
       'uid': 'Hyhyfd987698IUHGKDSh8d',
       'image': 'http://my-example-image.com'
}

Get Documents in a Collection

users = db.collection(u'User').stream()

for user in users:
    print(f'{user.id} => {user.to_dict()}')

. . . 

document => {'avatar': 'http://my-avatar-image.com', 'name': 'My Name'}
document1 => {'avatar': 'http://my-avatar-image.com', 'name': 'My Good Name'}

Get Documents from a Collection Group

users = db.collection(u'Users')

a_posts = users.document(u'A').collection(u'post')
a_posts.document().set({
    u'name': u'My Good Name',
    u'type': u'user'
})

b_posts = users.document(u'B').collection(u'post')
b_posts.document().set({
    u'name': u'My Best Name',
    u'type': u'user'
})

c_posts = users.document(u'C').collection(u'post')
c_posts.document().set({
    u'name': u'My Real Name',
    u'type': u'user'
})

names = db.collection_group(u'post')\
    .where(u'type', u'==', u'user')

all_users = names.stream()

for user in all_users:
    print(f'{user.id} => {user.to_dict()}')

Possible Error Message

You might receive this error message if you create the database and then try extracting the data straightaway. Wait a few minutes while the index is built in the background, and then try again.

FailedPrecondition: 400 The query requires a COLLECTION_GROUP_ASC index for collection . . That index is not ready yet. 
Related