我有一个数据库结构如下(为了这个问题的目的而简化):
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"}
...
我正在使用集合组查询来检索“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());
});
})
但现在我需要改进以上内容,以便能够过滤来自特定城市(例如巴黎)的订单。所以我尝试添加一个“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());
});
})
但这失败了,我收到以下消息:
Error: [Error: [firestore/failed-precondition] Operation was rejected because the system is not in a state required for the operation's execution. Ensure your query has been indexed via the Firebase console.]
我已经在我的 FireStore 数据库上设置了一个包含以下详细信息的复合索引:
Collection ID = orders_item_A
Fields indexed = address.city Ascending type Ascending
Status = Enabled
我不确定我做错了什么。我想知道问题是否出在“where”子句 (which should not be the problem) 中使用对象属性。所以我还用一个更简单的查询进行了测试,例如:
.where("type", "==", "A1")
但这也失败了。我做错了什么?
最佳答案
我发现了问题。我的错误显然是制作了一个“综合”索引(正如我在问题中提到的),因为它是单击“索引”时的起始页面。我应该制作一个“单字段”索引:
删除我现有的复合索引后,我创建了一个新的“单字段”索引,详细信息如下:
单击“下一步”并在下一个屏幕上“启用”“集合组范围”下的选项之一(我选择升序):
执行上述操作很重要,否则查询将无法进行。 然后一切都按预期工作,使用我的原始代码:
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());
});
})
注意:如果您碰巧删除了某个特定的“索引”,则需要一些时间(在某些情况下长达 10 分钟)才能准备就绪。在此期间,如果尝试为同一条目创建索引,您将收到错误消息。所以请稍等,过一段时间再试。
关于javascript - 在 FireStore 中过滤集合组查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62157759/