在不获取所有节点数据的情况下检查键是否存在

Check if a key exists without getting all node data

我将 Firebase 的实时数据库与节点一起使用,我发现检查密钥是否存在的唯一方法是 return 所有数据

{
  "salas" : {
    "sala01" : {
      "activa" : true,
      "fechaComienzo" : "2021-10-16 07:09:00Z",
      "fechaCreacion" : "2021-10-16 07:09:24Z",
      "nombre" : "test",
      "masInfo": {
        ...
      }
    },
    "sala02" : {
      "activa" : true,
      "fechaComienzo" : "2021-10-16 07:09:00Z",
      "fechaCreacion" : "2021-10-16 07:09:24Z",
      "nombre" : "test",
      "masInfo": {
        ...
      }
    }
  }
}
async function checkExists(_ref, key) {
    const q = query(_ref, ...[orderByKey(), equalTo(key)])
    const datos = await get(q);
    console.log('@info', q, datos);
    return datos.exists();
}

const _ref = ref(getDatabase())
checkExists(_ref, 'sala01')

对于上面的例子,如果我想知道 sala01 是否存在,它会给我每个节点及其后代。

我想知道是否有任何其他方法可以简单地检查 sala01 是否存在而不给我整个节点,或者是否有一些技巧可以使节点具有深度,就像我在 REST 中看到的那样API 文档,shallow

这种查询比需要的更复杂:

const q = query(_ref, ...[orderByKey(), equalTo(key)])

如果您已经知道节点的键,则无需使用查询,而是可以直接访问该键。

async function checkExists(_ref, key) {
    const ref = child(_ref, key)
    const datos = await get(ref);
    return datos.exists();
}

这不会读取整个 /_ref 节点,但 读取整个 /_ref/$key 节点。如果不读取路径,就无法测试该路径是否存在。