Why firestore does not return object when using where clause in chrome extension?

Viewed 68

I'm trying to filter some data from Firestore using chrome extension. My first code block works and gives the ch_id, but the second (filtered with where clause) is not returning object.

First code block. This works properly and gives message doc.data().ch_id as "ch001".

svrGetVids("ch001");
function svrGetVids(ch_id)
{
   try{
    var docRef = db.collection("channel")
    .doc("000000000000000000000001");
    docRef.get().then(function(doc) {
        if (doc.exists) {
            alert( doc.data().ch_id);
        } else {
            alert('no doc found');
        }
    }).catch(function(error) {
        alert(error.message);
    });
}catch(error)
{
    alert(error.message);
}

/*second code block. This does not return the object, and alerts 'no doc found'*/

 try{
    db
    .collection("channel")
    .where("ch_id",'==', ch_id)
    .get()
    .then(function(doc) {
        if (doc.exists) {
            alert( doc.data().ch_id);        
        } else {
            alert('no doc found');
        }
    }).catch(function(error) {
        alert('e1'+error.message);
    });
  }catch(error)
  {
     alert('e2'+error.message);
  }
}

Can anyone please find what I'm doing wrong in the second code block?

1 Answers

The reason is because there is a difference between the type of the object you are getting. The docRef.get() returns a DocumentSnapshot while db.collection("channel").where("ch_id",'==', ch_id).get() returns a QuerySnapshot, which does not have a exists property, as you can see in the documentation.

So if you want the same result, you will have to do something like this:

try{
    db.collection("channel")
      .where("ch_id",'==', ch_id)
      .get()
      .then(function(querySnapshot) {
          if (!querySnapshot.empty) {
              querySnapshot.foreach(function(doc) {
                  alert(doc.data().ch_id);        
              });
          } else {
              alert('no doc found');
          }
    }).catch(function(error) {
        alert('e1'+error.message);
    });
  }catch(error)
  {
     alert('e2'+error.message);
  }
Related