[英]How to get document by ID after insertion?
這個想法很簡單。 用戶正在將新文檔添加到集合中,然后希望在頁面上列出該文檔而無需刷新。 我知道我可以使用onSnapshot
同步所有文檔,但是這很重要,現在我只想按ID
獲取插入的文檔。
addWish = function() { let wish = document.getElementById("wish-text").value; if (wish && this.checkSignedIn()) { this.database.collection("wishes").add({ wish: wish, author: this.user.name, date: 0 - Date.now(), voteup: 1, votedown: 0 }).then(function(docRef) { console.log("Document written with ID: ", docRef.id); this.database.collection('wishes').doc(docRef.id).get().then(function (documentSnapshots) { this.renderWishes(documentSnapshots, 1); }.bind(this)).catch(function(error) { console.error("Error getting document: ", error); }); }.bind(this)).catch(function(error) { console.error("Error adding document: ", error); });
函數renderWishes
失敗。 然后其他所有操作也會失敗,例如foreach
:
renderWishes = function(querySnapshot, type) {
console.log(querySnapshot.docs[0].data());
querySnapshot.forEach(function(doc) {
let id = doc.id;
doc = doc.data(); //and after I simply display data with templates ${doc.author}
獲取文檔時出錯:TypeError:無法讀取未定義的屬性“ 0”
和
foreach`:“ firebase.js:131獲取文檔時出錯:TypeError:querySnapshot.forEach不是函數
有沒有機會解決這個問題? 還是無法從Firestore通過ID獲取文檔?
異步get()操作的結果是返回一個與您在代碼中期望的對象不同的對象。
在代碼中,您將以下對象放入新文檔中:
{
wish: wish,
author: this.user.name,
date: 0 - Date.now(),
voteup: 1,
votedown: 0
}
當您在add()之后立即獲取()該文檔時,您調用querySnapshot
的變量將包含一個DocumentSnapshot,其中包含的內容正是這些內容。 嘗試訪問時,DocumentSnapshot沒有docs
屬性。 這就是為什么您收到有關未定義錯誤的原因。 DocumentSnapshot具有id屬性 ,該屬性將為您提供剛獲取的文檔的ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.