My firestore document structure looks like this
doc1
{
name: 'Test',
categories: [
{
allNames: ['name1', 'name2', 'name3],
id: 'abcd'
},
{
allNames: ['name4', 'name5'],
id: 'xyz'
},
]
doc2
{
name: 'Test2',
categories: [
{
allNames: ['name7'],
id: 'abcd3'
},
{
allNames: ['name4', 'name5'],
id: 'xyz'
},
]
I am using the JS SDK and wanted to query all document with a certain category(id or name). So if I query with categories.id
equal to xyz
or categories.allNames
contains name1
, both the above documents should be returned.
Are both these queries possible or do I need to remodel my data ?
Thank you !
CodePudding user response:
You cannot query arrays that way. If you know the exact object then you could use array-contains
as shown below:
firestore.collection('col').where('categories', 'array-contains', {id: 'abc', allNames: ['name1']})
One solution would be to store another array which contains category IDs only like this:
{
name: 'Test1',
categories: [...],
categoryIds: ['abcd', 'xyz']
}
Now you can use arrayContains
even if you know the category ID only and not the whole object in categories array. The same method can be used for allNames.
Categories can also be made a sub-collection where each object in categories array would be a document. Then you can use Collection Group queries to find category documents with that ID or allNames and find parent document ID using the DocumentReference.