manidos
manidos

Reputation: 3464

How to get nested objects using Firestore REST API?

I'm sending REST API requests using axios package.

I can get a single document (for example, cities/cityId):

axios.get(`https://firestore.googleapis.com/v1/projects/<PROJECTIDHERE>/databases/(default)/documents/<COLLECTIONNAME>/<DOCID>`)

What I can't do is to get a nested document (for example, cities/cityId/streetId)

The database structure is very simple.

cities: {                 // COLLECTION
   cityId: {              // DOCUMENT
     streetId: {          // MAP
       buildingId: '...', // STRING
       ...
     },
     ...
   },
}

This article Google Firestore REST API examples suggests that it's possible to get nested objects using structured queries. Unfortunately, I've been trying to do it without any success.

Here's my not working code:

  getQuery ({ path, token }) {
    const url = 'https://firestore.googleapis.com/v1/projects/big-boobs/databases/(default)/documents:runQuery'
    const params = {
      from: [ { collectionId: 'cities' } ],
      select: {
        fields: [
          { fieldPath: 'cityId1.streetId' }
        ]
      }
    }
    const options = {
      method: 'get',
      url,
      params,
      paramsSerializer: function (params) {
        return Qs.stringify(params, { arrayFormat: 'brackets' })
      }
    }
    if (token) options.headers['Authorization'] = `Bearer ${token}`
    return axios(options)
  }

I'm getting an error:

{
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"from[][collectionId]\": Cannot bind query parameter. Field 'from[][collectionId]' could not be found in request message.\nInvalid JSON payload received. Unknown name \"select[fields][][fieldPath]\": Cannot bind query parameter. Field 'select[fields][][fieldPath]' could not be found in request message.",
}

Upvotes: 1

Views: 563

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317760

You can select individual fields from a document, but you can't select individual properties from a map field. I think you'll have to settle for getting the entire map called streetId.

If it's unacceptable to pull down the entire map, you can reorganize your data such that each streetId exists in its own document.

Upvotes: 1

Related Questions