1

I know how to query simple collection/doc like so:

const querySnapshot = await 
this.authenticationProvider.firestoreDb.collection("members").where("userId", 
"==", this.authenticationProvider.user.uid).get();

But could I fetch the data from an inner array using a condition on firestore? You can see that where I need to check the projects/memberList array and after that need to search the email. Could I do that?

enter image description here

Sampath
  • 63,341
  • 64
  • 307
  • 441
  • you cant query a document apparently https://github.com/angular/angularfire2/blob/master/docs/firestore/documents.md#querying – Suraj Rao Feb 20 '18 at 10:00
  • 1
    Good place to put a gif :) . You can deep down the array using a dot `.` check this [link](https://firebase.google.com/docs/firestore/solutions/arrays). But you have a dynamic list which increments. even though you dynamically query your data there is no way to `index` it and firestore throw error. – Hareesh Feb 20 '18 at 10:04
  • Actually, I need to retrieve the whole doc. But I need to give a search condition after 2 arrays there `projects/memberList` and after `email`. still, I need to retrieve the collection. Could I? @SurajRao – Sampath Feb 20 '18 at 10:12
  • Here the problem is how can I give the search criteria there due to 2 arrays? @SurajRao – Sampath Feb 20 '18 at 10:15
  • I don't think you can do that. You can fetch the document and then use TypeScript to filter out the ones you don't need. – javebratt Feb 20 '18 at 11:51
  • Yes, It seems I have to construct my arrays using this trick explained here no? https://firebase.google.com/docs/firestore/solutions/arrays Thanks @javebratt – Sampath Feb 20 '18 at 11:57

1 Answers1

2

You can't do that with an array. You will want to structure your data as an object, where each key is the userId. Firestore will index the object keys allowing you to run queries against them. Your data strucuture might look like:

firestore

Then you can run a query like this:

const userId = this.authenticationProvider.user.uid
ref.collection('members').where(`memberList.${userId}`, '==', true)

You can even embed additional data under each userId key (such as another object), then get all the documents of which that user is a member like so:

ref.orderBy(`memberList.${userId}`)
JeffD23
  • 8,318
  • 2
  • 32
  • 41
  • Thank you so much. This is awesome :) – Sampath Feb 20 '18 at 13:59
  • This is great - would there be a way of updating the membersList dynamically, or does it have to be done with a transaction? Something like: `db.collection('members').doc('id).update({ 'memberList.${userId}' : true })` – HJo Jul 10 '18 at 14:25
  • I've come across the solution to my comment: [Cloud Firestore: Update fields in nested objects with dynamic key](https://stackoverflow.com/questions/47295541/cloud-firestore-update-fields-in-nested-objects-with-dynamic-key) – HJo Jul 10 '18 at 15:55