Sha*_*tan 2 javascript firebase react-native google-cloud-firestore
我的数据库结构如下(为了解决这个问题而进行了简化):
Collection: item_A
-> Document: params = {someParameter: "value"}
-> Document: user_01
-> Sub-collection: orders_item_A
-> Document: order_AA = {type: "A1", address: {pincode: "000000", city:"Paris"}
-> Document: order_AB = {type: "A2", address: {pincode: "111111", city:"London"}
...
-> Document: user_02
-> Sub-collection: orders_item_A
-> Document: order_AC = {type: "A1", address: {pincode: "222222", city:"Berlin"}
-> Document: order_AD = {type: "A1", address: {pincode: "333333", city:"Paris"}
...
Run Code Online (Sandbox Code Playgroud)
我正在使用集合组查询来检索“item_A”下的所有订单(跨所有用户)。我可以通过以下方式让它发挥作用:
let orders = [];
await firestore()
.collectionGroup("orders_item_A")
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log(doc.id, ' => ', doc.data());
orders.push(doc.data());
});
})
Run Code Online (Sandbox Code Playgroud)
但现在我需要改进上述内容,以便能够过滤来自特定城市(例如巴黎)的订单。所以我尝试添加一个“where”子句,如下所示:
let orders = [];
await firestore()
.collectionGroup("orders_item_A")
.where("address.city", "==", "Paris")
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log(doc.id, ' => ', doc.data());
orders.push(doc.data());
});
})
Run Code Online (Sandbox Code Playgroud)
但这失败了,我收到以下消息:
错误:[错误:[firestore/failed-precondition] 操作被拒绝,因为系统未处于操作执行所需的状态。确保您的查询已通过 Firebase 控制台编入索引。]
我已经在 FireStore 数据库上设置了一个复合索引,其中包含以下详细信息:
集合 ID = order_item_A
索引字段 = 地址.城市 升序类型 升序
状态 = 已启用
我不确定我做错了什么。我想知道问题是否出在“where”子句中使用对象属性(这不应该是问题)。所以我还使用更简单的查询进行了测试,例如:
.where("type", "==", "A1")
Run Code Online (Sandbox Code Playgroud)
但这也失败了。我究竟做错了什么?
我解决了这个问题。我的错误显然是制作了“综合”索引(正如我在问题中提到的),因为它是单击“索引”时的打开页面。我应该制作一个“单字段”索引:
删除现有的复合索引后,我创建了一个新的“单字段”索引,详细信息如下:
单击“下一步”,然后在下一个屏幕上“启用”“集合组范围”下的选项之一(我选择“升序”):
执行上述操作很重要,否则查询将无法工作。然后一切都按预期工作,使用我的原始代码:
let orders = [];
await firestore()
.collectionGroup("orders_item_A")
.where("address.city", "==", "Paris")
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
console.log(doc.id, ' => ', doc.data());
orders.push(doc.data());
});
})
Run Code Online (Sandbox Code Playgroud)
注意:如果您碰巧删除了特定的“索引”,则需要一些时间(有时长达 10 分钟)才能准备好。在此期间,如果尝试为同一条目创建索引,您将收到错误消息。因此,请等待一段时间后重试。
| 归档时间: |
|
| 查看次数: |
3427 次 |
| 最近记录: |