londonfed
londonfed

Reputation: 1230

Find document by key only, in Firestore

I am currently converting my Firebase real-time live database to use the new version, Firestore.

I would like to find a document by key. Previously, in Firebase real-time I could do something like this:

getSingleRouteById (key) {
   const ref = firebaseDb.ref('/data/')
   // now search for data with that key several nested layers down
   return ref.child(key)
      .once('value')
      .then((snapshot) => {
         return snapshot.val()
     })
}

After reading the new docs I can't find a way to achieve this in Firestore. Please, note I only know the key, so I need to search all documents, without knowing the actual path/reference.

Upvotes: 2

Views: 3246

Answers (1)

Dan McGrath
Dan McGrath

Reputation: 42038

There isn't a native way to do this. Part of the issue is there is no uniqueness to key across multiple paths, so when looking for the key 'key' in /data/ you could have /data/123/key and /data/231/key, meaning there are multiple possible answers.

The only way to achieve this would be to create your own inverted index. Whenever you create a document, use say Cloud Functions to automatically add a document to /keys/ with the id of key and update a field called paths to include the full path the key. paths should be map.

You can support deletions to by listening for that event and updating the inverted index.

For the above example, you would then have a document in /keys/ with the following:

Id: key
paths: {'/data/123/key' = true,
        '/data/231/key' = true}

Upvotes: 1

Related Questions