2017-10-11 240 views
1

這裏是我的數據的圖片: enter image description here火力地堡雲公司的FireStore查詢沒有找到我的文檔

我試圖得到該文檔。這工作:

var docRef = db.collection('users').doc('jPDKwHyrFNXNTFI5qgOY'); 
docRef.get().then(function(doc) { 
    if (doc.exists) { 
    console.log("Document data:", doc.data()); 
    } else { 
    console.log("No such document!"); 
    } 
}).catch(function(error) { 
    console.log("Error getting document:", error); 
}); 

它返回:

enter image description here

即,如果我知道文檔的關鍵,我可以得到該文檔。

這不起作用:

db.collection('users').where('uid', '==', 'bcmrZDO0X5N6kB38MqhUJZ11OzA3') 
.get().then(function(querySnapshot) { 
    if (querySnapshot.exists) { 
    console.log(querySnapshot.data); 
    } else { 
    console.log("No such document!"); 
    } 
}) 
.catch(function(error) { 
    console.log("Error getting document: ", error); 
}); 

它只是返回No such document!這有什麼錯我的查詢?

+0

請用於代碼的語言標記。這是JavaScript。 – tadman

回答

3

兩個請求的不同之處在於,在第一種情況下,您將檢索一個文檔,該文檔爲您提供了一個DocumentSnapshot,該文檔具有exists屬性和data()方法。

在你做一個查詢第二種情況下,它給你一個QuerySnapshot必須被從DocumentSnapshot不同的處理。您可以獲取文檔列表/文檔集合,而不是單個文檔。您可以檢查數據是否已經被使用emptysize性檢索,然後通過結果使用forEach方法或通過docs陣列打算去:

db.collection('users').where('uid', '==', 'bcmrZDO0X5N6kB38MqhUJZ11OzA3') 
.get().then(function(querySnapshot) { 
    if (querySnapshot.size > 0) { 
    // Contents of first document 
    console.log(querySnapshot.docs[0].data()); 
    } else { 
    console.log("No such document!"); 
    } 
}) 
.catch(function(error) { 
    console.log("Error getting document: ", error); 
}); 
+0

謝謝,但它仍然無法正常工作。用你的代碼,我得到這個錯誤信息:「NOT_FOUND,這個文件不存在。在調用doc.data()之前檢查doc.exists以確保文件存在。」我試着添加「console.log(querySnapshot.exists);」並回到「未定義」。這聽起來像我的查詢是不好的。有任何想法嗎? –

+0

如果您查看了我鏈接到的'QuerySnapshot'文檔,您將會看到它沒有'exist'屬性,所以它總是未定義的。我已經寫了一篇簡短的文章,可能會澄清一些事情:https://medium.com/@scarygami/cloud-firestore-quicktip-documentsnapshot-vs-querysnapshot-70aef6d57ab3 – Scarygami

+0

這工作!我把你的中篇文章upvoted,這很清楚。 –