How to create subcollection indexes in Cloud Firestore?

I looked at the Cloud Firestore documentation and looked at the documentation, but found nothing about how to declare subcomponent indexes. I said something like this

...{ "collectionId": "user/{uid}/feeds", "fields": [..] }... 

and on the index tab it is saved as

 __escuser~1{uid}~1feeds__ 

I don’t know if I created it correctly or not.

+7
firebase google-cloud-firestore
source share
1 answer

When you go to create the index, it actually tells you to run the query that you want to create the index at a time manually, and then it will generate a URL that you can copy in the et voila browser!

enter image description here

Here's how you do it:

  • Create a new directory
  • npm init
  • npm i --save firebase-admin
  • Create index.js
  • Put the following function in the document

     const admin = require('firebase-admin'); const serviceAccount = require('./firebase-creds.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: 'https://projectId.firebaseio.com' }); function runQuery() { db .collection('users') .doc(someRandomUserId) .collection('feed') .where('read', '==', false) .where('timestamp', '<=', 1509889854742) //Or something else .get() .then(doc => { console.log(doc.data()); }) .catch(error => console.log(error)); }; runQuery(); 
  • Run node index.js

This would concern this:

{ Error: The query requires an index. You can create it here: https://console.firebase.google.com/project/project-projectID/database/firestore/indexes?create_index=longRandomString ...}

Copy the link and paste it into your browser.

enter image description here

Update

To add an index manually (via the CLI), you can do the following:

 { "indexes": [ { "collectionId": "feed", "fields": [ { "fieldPath": "read", "mode": "ASCENDING" }, { "fieldPath": "timestamp", "mode": "ASCENDING" }, ... ] } ] } 

Or just go to the admin panel in your database and add an index for feeds there.

+7
source share

All Articles