Search code examples
angulargoogle-cloud-firestoreionic4

Ionic 4 Firestore is it possible to read only a part of a document?


I hope you're ok! Thanks for reading.

Edited the question.

Say one document in firestore has objects stored as follows:

someida: {name: steve, alias: cap, etc}
someidb: {name: tony, alias: iron, etc}
someidc: {name: nat, alias: black, etc}
someidetc

And I know all the "someids", I'm guessing the answer might be no, but

Is it possible to write a query that would read only what's inside one of those someids'?

Currently I can get the data I need but after reading all the document and coding to find it and was wondering if it would be possible to avoid that, and just read the contents of one object since I have the "someid".

Already a great reply was posted, just wondering if there's any other suggestion.

Thank too many in advance! Best!


Solution

  • The easiest way would be to restructure your document a bit. Instead of storing each "someid" as a property, create an array of maps as a single property in the Firestore document. For example, the following would be how your document would look like:

    ids: [
          {id: someida, name: steve, alias: cap, etc},
          {id: someidb, name: tony, alias: iron, etc},
          {id: someidc, name: nat, alias: black, etc}
    ]
    

    where id, name, alias are properties of an object, and ids is an array of the type of that object.

    Now, you can easily extract the data you need from this array in your app. Since you are probably using AngularFire, you can retrieve this document by calling the following API in ngOnInit:

    ngOnInit() {
      this.users = await this.angularFirestore.collection(YOUR_COLLECTION).doc(YOUR_DOCUMENT).get()
        .pipe(map(result => result.data().ids as Array<OBJECT_TYPE>))
        .toPromise();
    }
    
    getAlias(requestedId: string) {
      return this.users.find(ob => ob.id === requestedId).alias;
    }
    
    isUserAvailable(requestedId: string): boolean {
      return !!this.users.find(ob => ob.id === requestedId);
    }
    

    To get the alias of "someidc", you can call the following function: this.getAlias("someidc")

    And to find out whether certain id is available or not: this.isUserAvailable("someida")

    Of course, make sure to call those functions after you've made your call to Firestore. ngOnInit should take care of that for you.