簡體   English   中英

Firestore:無法從查詢中獲取文檔 - doc.data 不是函數

[英]Firestore: Unable to fetch document from query - doc.data is not a function

這里 usersList 包含人員的用戶名列表, androidNotificationToken 是用戶文檔中包含發送通知的令牌的字段。

 const registrationTokens=[]; const indexOfSender=usersList.indexOf(senderUsername); // to remove the name of person sending message let removedUsername=usersList.splice(indexOfSender,1); usersList.forEach(async(element)=>{ const userRef = admin.firestore().collection('users').where("username","==",element); const doc = await userRef.get(); registrationTokens.push(doc.data().androidNotificationToken); });
運行雲計算時收到的錯誤是:-

 TypeError: doc.data is not a function at usersList.forEach (/workspace/index.js:191:37) at process._tickCallback (internal/process/next_tick.js:68:7)

userRef.get()將返回一個QuerySnapshot (不是DocumentSnapshot )對象,該對象可以包含從查詢中匹配的 0 個或多個文檔。 使用 QuerySnapshot 提供的 API 來查找結果文檔,即使您只需要一個文檔。

如果您期望查詢中只有一個文檔,您至少應該在索引到結果集之前驗證您是否獲得了一個文檔。

const query = admin.firestore().collection('users').where("username","==",element);
const qsnapshot = await query.get();
if (qsnapshot.docs.length > 0) {
    const doc = qsnapshot.docs[0];
    const data = doc.data();
}
else {
    // decide what you want to do if the query returns nothing
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM