jrnxf
jrnxf

Reputation: 964

Firestore/Rxfire - Query collection then subscribe to array of sub observables

I have a chat collection in firestore that holds messages. Each message has a userUid attached to it. What I'd like to accomplish is the following:

  1. Query the chat collection for an array of every message

  2. Iterate through each message and query the corresponding user doc in order to append user information onto the message

  3. Have one single subscribe that provides the original array of messages now with the added information

  4. (If possible - combineLatest?) each time a message is added it would be ideal to only query the user collection for the new message

The following snippet is what I'm working with at the moment:

const chatRef = db.collection('chat')
const messageUser$ = collectionData(chatRef, 'id')
    .pipe(
        switchMap(messages => {
            return forkJoin(...messages.map(m => {
                const userRef = db.collection('users').doc(m.userUid)
                return docData(userRef)
                    .pipe(
                        map(user => ({ ...user, ...m }))
                    )
            }))
        })
    )
messageUser$.subscribe(data => console.log('data', data))

I worked with a friend to come up with the two working solutions below, but neither worked when configured for my application

https://stackblitz.com/edit/rxjs-nzn11o

Upvotes: 1

Views: 375

Answers (1)

jrnxf
jrnxf

Reputation: 964

Got it!

collectionData(db.collection('chat'))
    .pipe(
        switchMap(messages =>
            combineLatest(
                messages.map(m =>
                    docData(db.collection('users').doc(m.userUid)).pipe(
                        map(user => ({ ...user, ...m }))
                    )
                )
            )
        )
    )
    .subscribe(enhancedMessages => console.log(enhancedMessages))

Upvotes: 3

Related Questions