Home > Blockchain >  Firebase: How to get document in sub collection without the parent key
Firebase: How to get document in sub collection without the parent key

Time:10-24

I need to perform a query to get the oldest document in a sub collection. I want to perform this query with few reads as possible. DB description: Based on Firebase. Collection of devices. Each device holds a collection of call-backs. For a specific device I need to fetch the oldest call-back (call-backs has timestamp).

I think I know how to perform this query using the device Unique ID, But I want to do it by filtering by some field of the device, this field is also unique. I was able to do it by querying the device with all of his call-backs but this will charge me for more reads then actually needed.

Query that works using ID:

  admin
    .firestore()
    .collection("devices/{device_id}/callbacks")
    .{order_by_timestamp}
    .limit(1)
    .get()
    .then((data) => {
      let callbacks = [];
      data.forEach((doc) => {
        callbacks.push(doc.data());
      });

      return res.json(callbacks);
    })
    .catch((err) => console.error(err));

CodePudding user response:

If that field in devices collection is unique then you can fetch ID of that device first and then proceed with your existing logic as shown below:

async function getOldestCallback(thatFieldValue) {
  const device = await admin.firestore().collection("devices").where("thatField", "==", thatFieldValue).get()

  if (device.empty) return false;
  
  const deviceId = device[0]["id"];

  // existing function
}

This should incur 2 reads (1 for device document and 1 for oldest callback if it exist).

Additionally, since you are limiting number of docs to be returned to 1 then you can use [0] instead of using a forEach loop.

const callbacks = [ data[0].data() ]
  • Related