如何解决Firestore db:查询数组以查找具有特定值的文档
如果我像下面这样查询,它会按预期返回文档。 我也知道 firestore 查询仅在完整对象匹配时返回结果。
return firestore()
.collection(`stores`)
.where('servicesList','array-contains-any',[
{
price: 24,serviceName: 'service1',},])
.onSnapshot((querySnapshot) => {
...
});
});
我有这些数组的商店集合,我需要在其中对过滤器进行不同的查询。
e.g. return all stores where Service Name = "Service1" and Price < 20
or return all stores where price > 20 etc..
我的文档结构是这样的: document structure
实现这一目标的有效方法是什么?
一个解决方案是在第一次加载时获取所有存储并在客户端进行过滤。 我想知道这是否可以使用查询来完成。
谢谢
解决方法
这在 Firestore 查询中是不可能完成的,正如您在此 community answer 中看到的那样,您只能查询整个对象,而不能查询其中的单个字段。
对于您提议的那些更复杂的查询,您有 2 个选项,要么按照您提到的在客户端执行所有操作,要么更改您的 Firestore 结构。既然你已经提到你知道如何做第一个选项,我将解释我将如何处理后者,你可以尝试这样的结构:
Store Collection
field1
...
fieldN
serviceIds:[]
ServicesOffered SubCollection
serviceId
price
Service Collection
serviceName
因此,一个单独的 Service 集合,只有 serviceName,一个 Store Collection 有一个 serviceUids 数组,它引用了 Service 集合的文档,以及一个 ServicesOffered 子集合,它给出了该服务在该商店中的具体价格。使用此结构,您可以像这样查询建议的查询:
firestore()
.collection(`services`)
.where('serviceName','==',"service1")
.get()
.then(function(documentSnapshot) => {
//This is the Id of the service to be searched
var id = documentSnapshot.id;
firestore().collection(`stores`)
.where('servicesList','array-contains',id)
.get()
.then(function(querySnapshot) => {
//query with the results of every store that contains the service
querySnapshot.forEach(function(doc) {
firestore().collection(`stores`)
.doc(doc.id)
.collection(`servicesOffered`)
.where('serviceId',id)
.where('price','>',20)
.get()
.then(function(documentFinalSnapshot) => {
// This is the price filter result
if (documentFinalSnapshot.exists) {
//add it to your return
}
})
});
});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。