【问题标题】:Firebase query example returns useless objectFirebase 查询示例返回无用的对象
【发布时间】:2019-02-09 13:36:02
【问题描述】:

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

这是我得到的结果:

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

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

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

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

    你实际上不应该直接使用这个对象,而是:

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

    • 或者,使用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);
      });
    

    【讨论】:

      猜你喜欢
      • 2019-01-07
      • 2020-12-07
      • 2018-11-11
      • 1970-01-01
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      相关资源
      最近更新 更多