首页 > 解决方案 > 为什么在chrome扩展中使用where子句时firestore不返回对象?

问题描述

我正在尝试使用 chrome 扩展从 Firestore 中过滤一些数据。我的第一个代码块有效并给出了 ch_id,但第二个(使用 where 子句过滤)没有返回对象。

第一个代码块。这可以正常工作并将消息 doc.data().ch_id 作为“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);
  }
}

谁能在第二个代码块中找到我做错了什么?

标签: javascriptgoogle-chrome-extensiongoogle-cloud-firestore

解决方案


原因是因为你得到的对象的类型不同。return docRef.get()a DocumentSnapshotwhiledb.collection("channel").where("ch_id",'==', ch_id).get()返回 a QuerySnapshot,它没有 exists 属性,如您在文档中所见。

因此,如果您想要相同的结果,则必须执行以下操作:

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);
  }

推荐阅读