0

I am using a real-time database and have the following structure:

{
  "users": {
     "1234": {
       "name": "Joe",
       "externalId": "384738473847",
      },
      "5678": { ... },
      "5555": { ... }
  }
}
        

I now want to access a user via the externalId and I am using the following to access this object:

const snapshot = await admin.database().ref(`/users/`).orderByChild('externalId').equalTo(`${someId}`).once('value')        

This will return me the following:

{
    "1234": {
        “name”:Joe,
        “externalId:”384738473847"
    }
} 

I would now would like to access the object (containing the name and externalId) without knowing the id (which is 1234).

I currently have this solution:

const rootValue = Object.keys(userSnapshot.val())[0]
const user = userSnapshot.val()[rootValue]

Which works, but I read that this is not the optimal way to do this. Is there a better way to access the object?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
José
  • 3,112
  • 1
  • 29
  • 42

1 Answers1

1

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

Your code needs to handle the list, and the best way is to use the built-in Snapshot.forEach operation:

const snapshot = await admin.database().ref(`/users/`).orderByChild('externalId').equalTo(`${someId}`).once('value')       
snapshot.forEach((userSnapshot) => {
  console.log(userSnapshot.key);
  console.log(userSnapshot.val());
  console.log(userSnapshot.val().name, userSnapshot.val().externalId);
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807