Bao Tran
Bao Tran

Reputation: 109

Firebase query: "where" clause is not working, keep returning all documents

Fetching member with id == "1112" and it is not working

var query = this.afs.collection('members', ref => ref.where('id', '==', "1112"))

query.ref.get().then(doc => {
   doc.forEach(postDoc => {
     console.log(postDoc.data());
   });
})

Firestore Result

Upvotes: 1

Views: 2134

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 599706

You're taking the query and then ask for its ref, which returns the collection that you created the query on. This means that you're calling get on the entire collection, which returns alls documents.

To only get the documents matching the conditions in your query, call get straight on the query. So:

query.get().then(doc => {
  ...

Alternatively you can bypass AngularFire2, since it has no benefits in this scenario. That means you end up with:

ref.where('id', '==', "1112").get().then(doc => {
  ...

Upvotes: 0

Ronnie Smith
Ronnie Smith

Reputation: 18595

normally you define a ref that points to either a document or a collection, and you may add a .where. You fire .get on the ref. ...Rewrite it to say

var ref = [whatever SDK/homepath].firestore.collection('members).where('id', '==', "1112");

then pass that ref to your .get. and NOTE you appear to be storing numbers as strings which can negatively impact / throw off queries.

Upvotes: 1

Related Questions