【问题标题】:Firestore: Unable to fetch document from query - doc.data is not a functionFirestore:无法从查询中获取文档 - doc.data 不是函数
【发布时间】:2020-11-19 16:14:53
【问题描述】:

这里的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)

【问题讨论】:

  • 在 Stack Overflow 上,请不要显示文字图片。将文本复制到问题中,以便于阅读、复制和搜索。
  • 好的,下次我会处理的
  • 这次您可以通过编辑问题来删除屏幕截图并添加文本来做到这一点。问题底部有一个编辑链接。
  • 将图片改为文字

标签: javascript node.js google-cloud-firestore google-cloud-functions


【解决方案1】:

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-07
    • 2020-01-04
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    相关资源
    最近更新 更多