在 Firebase 函数中查询嵌套文档
Query nested documents in Firebase functions
我已经苦苦挣扎了几个晚上,所以我希望有人能帮助我,这对我来说听起来并不复杂。我正在使用来自外部方的 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();
但是 returns 500 内部服务器错误。
有什么方法可以在 Firebase 函数中查询搜索嵌套文档?
您要查找的是 collection group query,它允许您查询具有特定名称的所有集合(例如您的所有 Companies
)。
Firestore 查询只能包含它们 return 文档的条件,因此您将无法检查 Users
文档中的 customerId
字段。相反,您需要在每个 Companies
文档中复制 customerId
值,以便您可以将其包含在集合组查询中。
一旦你这样做了,查询就会变成这样:
db.collectionGroup('Companies').where('customerId', '==', '...').where(...).get()
我已经苦苦挣扎了几个晚上,所以我希望有人能帮助我,这对我来说听起来并不复杂。我正在使用来自外部方的 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();
但是 returns 500 内部服务器错误。
有什么方法可以在 Firebase 函数中查询搜索嵌套文档?
您要查找的是 collection group query,它允许您查询具有特定名称的所有集合(例如您的所有 Companies
)。
Firestore 查询只能包含它们 return 文档的条件,因此您将无法检查 Users
文档中的 customerId
字段。相反,您需要在每个 Companies
文档中复制 customerId
值,以便您可以将其包含在集合组查询中。
一旦你这样做了,查询就会变成这样:
db.collectionGroup('Companies').where('customerId', '==', '...').where(...).get()