I have googled and checked the Cloud Firestore documentation and found nothing about how to declare subcollections indexes. I have declared something like this
...{
"collectionId": "user/{uid}/feeds",
"fields": [..]
}...
and in the indexes tab it is stored like this
__escuser~1{uid}~1feeds__
No idea if I created properly it or not.
Automatic indexing For each map field, Cloud Firestore creates one collection-scope ascending index and one descending index for each non-array and non-map subfield in the map. For each array field in a document, Cloud Firestore creates and maintains a collection-scope array-contains index.
The solution goes: Get the interested document (doc) and then: doc. ref. collection('Collection_Name'). add('Object_to_be_added') It is advisable to include a then/catch after the promise.
A subcollection is a collection associated with a specific document. Note: You can query across subcollections with the same collection ID by using Collection Group Queries. You can create a subcollection called messages for every room document in your rooms collection: collections_bookmark rooms. class roomA.
When you go to create an index, it actually tells you to run the query you want to create an index for once manually and then it will generate a URL you can copy paste into the browser et voila!
This is how you do it:
npm init
npm i --save firebase-admin
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 will spit someting like this out:
{ 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.
Update
To add the index manually (via the CLI) you can do the following:
{
"indexes": [
{
"collectionId": "feed",
"fields": [
{ "fieldPath": "read", "mode": "ASCENDING" },
{ "fieldPath": "timestamp", "mode": "ASCENDING" },
...
]
}
]
}
Or simply go in to the admin panel in your database and add the index for feeds there.
This appears to be answered by @michael-bleigh here: https://stackoverflow.com/a/47165007/2511985
Cloud Firestore indexes are based on collection names, not full collection paths. So if you want to create indexes on
users/{id}/messages
, the correct way to do this is to create an index onmessages
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With