Firestore where 'array-contains' query doesn't work with references

女生的网名这么多〃 提交于 2019-12-12 12:09:12

问题


I have a collection 'chats' with a members array which contains users participating in the chat. The problem is I want to get all chats where the current user is participating.

I do this with this query:

getUserChats(): Observable<Chat[]> {
    return this.auth.currUser
      .pipe(
        take(1),
        switchMap(user => this.afs
            .collection('chats', ref => ref.where('members', 'array-contains', `/users/${user.uid}`))
            .snapshotChanges()
            .pipe(
              map(actions => {
                return actions.map(action => {
                  const data = action.payload.doc.data() as Chat;
                  const id = action.payload.doc.id;
                  return {id, ...data};
                });
              })
            ) as Observable<Chat[]>
        )
      );
  }

This works well for strings, but doesn't work with References. How can I also make it work on References?

The green works the red one doesn't work

Green: String Red: Reference


回答1:


It works with strings because you're passing as the third argument to the where() function the following argument:

/users/${user.uid}

Which is of type String. If you want to work with references as well, instead of a String, pass an actual DocumentReference object.




回答2:


@Alex Mamo answer is right, you need a DocumentReference.

NOTE: YOU CAN'T CREATE ONE YOURSELF!

You have to get the reference by querying firebase!

Code:

return this.auth.currUser
      .pipe(
        take(1),
        switchMap(user => this.afs
            .collection('chats', ref => ref.where('members', 'array-contains', this.afs
              .collection('users')
              .doc<User>(user.uid)
              .ref))
            .snapshotChanges()
            .pipe(
              map(actions => {
                return actions.map(action => {
                  const data = action.payload.doc.data() as Chat;
                  const id = action.payload.doc.id;
                  return {id, ...data};
                });
              })
            ) as Observable<Chat[]>
        )
      );

The crucial part is the 'value' part which is:

this.afs
              .collection('users')
              .doc<User>(user.uid)
              .ref

You query and THEN get the reference with .ref!

That's it! That's how you query for a DocumentReference!



来源:https://stackoverflow.com/questions/53205155/firestore-where-array-contains-query-doesnt-work-with-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!