首页 > 解决方案 > Firebase 查询示例返回无用的对象

问题描述

我正在尝试使用查询从 firebase 文档中获取示例,但它似乎不起作用。我正在使用云火库。

这是我得到的结果:查询结果

var citiesRef = db.collection("cities");

citiesRef.doc("SF").set({
    name: "San Francisco", state: "CA", country: "USA",
    capital: false, population: 860000,
    regions: ["west_coast", "norcal"] });
citiesRef.doc("LA").set({
    name: "Los Angeles", state: "CA", country: "USA",
    capital: false, population: 3900000,
    regions: ["west_coast", "socal"] });
citiesRef.doc("DC").set({
    name: "Washington, D.C.", state: null, country: "USA",
    capital: true, population: 680000,
    regions: ["east_coast"] });
citiesRef.doc("TOK").set({
    name: "Tokyo", state: null, country: "Japan",
    capital: true, population: 9000000,
    regions: ["kanto", "honshu"] });
citiesRef.doc("BJ").set({
    name: "Beijing", state: null, country: "China",
    capital: true, population: 21500000,
    regions: ["jingjinji", "hebei"] });


// Create a reference to the cities collection
var citiesRef = db.collection("cities");

// Create a query against the collection.
var query = citiesRef.where("state", "==", "CA");

console.log(query);

我期望记录一个代表包含指定值的文档的对象。但结果总是相同的(见附件),即使我搜索一个不存在的值。这是为什么?我希望有人可以解释这里发生了什么以及为什么文档中提供的示例不起作用...

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


这是因为,使用问题中的代码,您定义(和console.log())一个Query对象。

您实际上不应该直接使用此对象,而是:

  • 调用get()方法执行查询并获取结果文档(通过 a QuerySnapshot);
  • 使用方法为QuerySnapshot事件附加监听器onSnapshot()

  • 或者,使用 , 等其他方法优化此where()查询orderBy()...

您可以在此处找到完整的文档:https ://firebase.google.com/docs/reference/js/firebase.firestore.Query

因此,更具体地说,使用您当前的代码,您应该执行以下操作:

var query = citiesRef.where("state", "==", "CA");

query.get()
  .then(snapshot => {
    if (!snapshot.empty) {
        snapshot.forEach(doc => {
          console.log(doc.id, '=>', doc.data());
        });
    } else {
        console.log('No document corresponding to the query');
    } 
  })
  .catch(err => {
     console.log('Error getting documents', err);
  });

推荐阅读