How to get all documents in Firebase collection with specific value?

Viewed 40

I have a firebase collection with documents containing info of all posts from users, i am wanting to retrieve all posts from specific user.

Each document has the owners UID, is there a way to query firebase to get all documents in a collection with the ownersUID being the same as the current users UID.

For example something like this.

firebase.collection("collectionName").getdocumentswhere("OwnerUID" == user.UID)

Which i can then use to display and do what i want with

Cheers in advance!

1 Answers

You can query all the documents that have the UID in its field by using the where() method. I'll assume that you're still using the v8 syntax of Firebase Firestore as you're using the dot notation. See sample code below:

// Create a query against the collection.
var query = firebase.collection("collectionName").where("OwnerUID", "==", user.UID);

// Execute the query
query
.get()
.then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
    });
})
.catch((error) => {
    console.log("Error getting documents: ", error);
});

The above snippet will log all the document fields OwnerUID that match with the user.UID.


For more information, you may checkout this documentation.

Related