"错误":"索引未定义,添加".indexOn"

Kno*_*uch 21 firebase firebase-security firebase-realtime-database

我在Firebase中创建了一个数据库,如下所示:

数据库结构

现在我进入REST客户端并发出以下查询:

https://movielens3.firebaseio.com/movieLens/users.json?orderBy="age"&startAt=25&print=pretty
Run Code Online (Sandbox Code Playgroud)

它给了我一个错误:

"error": "Index not defined, add ".indexOn": "age", for path "/movieLens/users", to the rules"
Run Code Online (Sandbox Code Playgroud)

所以我进入规则部分并定义此规则:

{
    "rules": {
        "users" : {
          ".indexOn": ["age", "gender", "occupation", "zipCode"]
        },
        ".read": true,
        ".write": true
    }
}
Run Code Online (Sandbox Code Playgroud)

但我仍然得到同样的错误.

Fra*_*len 24

你正在定义索引/users.users树的根目录下没有子节点,因此这些索引将为空.

您正在查询/movieLens/users,因此应该定义索引:

{
    "rules": {
        "movieLens": {
            "users" : {
                ".indexOn": ["age", "gender", "occupation", "zipCode"]
            },
            ".read": true,
            ".write": true
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

评论中的问题更新:

您将用户的年龄存储为字符串,因此无法将其过滤为数字.解决方案是修复您的数据并将其存储为数字.

但与此同时,这个查询有点起作用:

https://movielens3.firebaseio.com/movieLens/users.json?orderBy="age"&equalTo="35"
Run Code Online (Sandbox Code Playgroud)

在JavaScript中:

ref
  .orderByChild('age')
  .startAt('35')
  .limitToFirst(3)
  .once('value', function(s) { 
    console.log(JSON.stringify(s.val(), null, '  ')); 
  }, function(error) { 
    if(error) console.error(error); 
  })
Run Code Online (Sandbox Code Playgroud)

"有点"是它做了词汇排序,而不是数字排序.修复数据以获得真正的解决方案.

请注意,您还将数据存储为数组,从而忽略了Firebase的最佳做法.这在REST API中已经给我带来了问题,这就是为什么我放弃了print=pretty.我强烈建议您从头到尾阅读针对JavaScript开发人员Firebase编程指南,并遵循其中的建议.现在花费的几个小时,将阻止许多小时的问题.