1. 20
    Query and Filter Documents from Firestore by userId with query()
    2m 51s

Query and Filter Documents from Firestore by userId with query()

Jorge Vergara
InstructorJorge Vergara
Share this video with your friends

Social Share Links

Send Tweet

Now that tasks are actually associated with a user in our database, we want to only show a user their own tasks.

To do this we'll revisit our task list and make some changes to use the query() and where() methods to filter our list before we get it from the database.

We'll learn how to pass our user's ID to a query and fetch only the tasks that belong to that user. Because Firebase uses Observables, you'll also see how we handle and change observables in Angular.

Man 1: [0:01] Now that we started adding users to our tasks, we see that this task map out outflow has my user id here but this other task that I have here that says similar task for testing has a different user id. When I go into my application, I'm able to see both of them.

[0:22] Ideally, I will only be able to see my own tasks. For that we are going to go into our tasks page and we are going to check our tasks initialization. Here, I'm creating a reference to the tasks collection and then I'm using collection data to get the entire task list as an observable.

[0:46] We are going to bring AngularFire authentication here, and we are going to do a little more work in the task initialization. Here, we are going to start our observable stream by getting our user. We can get our user with the authState function that comes in AngularFire authentication.

[1:07] AuthState takes a parameter, the AngularFire authentication instance, and it returns an observable of the user. Since this is an observable, we can pipe into it. Here, we are going to get our user, and we are going to return a new observable. This is the collection data that we were returning before.

[1:34] Collection data takes a couple of different things. One can be the reference to the task that we are getting, but the other one can be a query. We are going to change this reference right here for a query. For that, we can use the query method from AngularFire. Our query is going to take two parameters.

[2:00] First, it's the same as we had before, it's the collection reference. Now that we have the collection reference, we can start passing our conditions. For conditions, AngularFire has a specific clause that's called where. This takes three parameters.

[2:19] The first parameter is the name of the property that we are going to evaluate against. In our case, it's user. The second parameter, it's going to be the operation that we are going to do. We are going to check for equality. The last parameter is the value against we are going to compare. In our case, it's going to be user UID. Now, when I save the application and reload, you see that now I only see my task.