Home > Enterprise >  Check if a key exists without getting all node data
Check if a key exists without getting all node data

Time:11-29

I am using Firebase's Realtime Database with node and I find that the only way to check that a key exists is to return all the data

{
  "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')

With the above example, if I want to know if sala01 exists, it brings me every node with its descendants.

I wonder if there is any other way to simply check if sala01 exists without bringing me the entire node or if there is some trick to bring a node with a depth as if I have seen in the REST API documentation, shallow

CodePudding user response:

This sort of query is more complex than needed:

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

If you know the key of a node already, you don't need to use a query, but can access that key directly.

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

This won't read read the entire /_ref node, but will read the entire /_ref/$key node. There is no way to test for the existence of a path without reading that path.

  • Related