【发布时间】:2021-11-25 05:50:09
【问题描述】:
我已经挣扎了几个晚上,所以我希望有人可以帮助我,这对我来说听起来并不太复杂。我正在使用来自外部方的 webhook,每次更改帐户时都会触发 Firebase 功能。当它被触发时,它需要搜索和更新相关的 Firebase 对象。
我的数据库结构如下:
- Users (collection)
- user (document) < Includes the customerId from the webhook
- Companies (collection)
- company (document) < Includes the companyId from the webhook
获取相关用户我已经完成:const userRef = db.collection('Users').where('customerId', '==', 'webhook.customerId').get();
这在查询相关用户时有效,但下一步是在集合Companies 中搜索正确的公司文档。这是我卡住的部分。
为了实现这一点,我尝试将它串起来(大声笑),例如:const userRef = db.collection('Users').where('customerId', '==', 'webhook.customerId').doc().collection('Companies').where(etc... etc... 这不起作用。
我也尝试过const companiesRef = db.collectionGroup('Companies').where('companyId', '==', 'webhook.companyId').get();,但这会返回 500 内部服务器错误。
我可以通过什么方式在 Firebase 函数中查询搜索嵌套文档?
【问题讨论】:
-
您需要获取单个文档才能检索其子集合。
.where将返回一个查询快照,我认为.doc()语法用于在创建新文档时生成文档引用。If no path is specified, an automatically-generated unique ID will be used for the returned DocumentReference -
如果您不知道用户的密钥(这就是我假设您使用 where 子句的原因),那么从结果列表中获取第一个也是唯一一个文档。然后像上面一样访问子集合。
-
感谢您的评论!我找到了一种在 webhook 请求中包含密钥的方法。这似乎是目前唯一的解决方法。您知道如何在搜索相关父文档后返回带有路径的子文档吗?
-
是的,只需使用 snapshot.forEach。既然你知道只有一场比赛。
标签: node.js firebase google-cloud-firestore google-cloud-functions