Search code examples
javascriptgoogle-cloud-firestoreionic4angularfire

Ionic AngularFirestoreCollection Property 'id' does not exist type 'QueryDocumentSnapshot<Todo>'


I am fairly new to Ionic and I am trying to connect to Firebase database, and while writing the snapshotChange(). I hit an error.

Property 'id' does not exist on type 'QueryDocumentSnapshot<Todo>'.

The code is below,

export interface Todo {
  id?: string;
  task: string;
  priority: number;
  createdAt: number;
}


export class TodoPage implements OnInit {
  private todosCollection: AngularFirestoreCollection<Todo>;

  private todos: Observable<Todo[]>;

  constructor(db: AngularFirestore) {
    this.todosCollection = db.collection<Todo>("todos");

    this.todos = this.todosCollection.snapshotChanges().pipe(
      map((actions) => {
        return actions.map((a) => {
          const data = a.payload.doc.data();
          const id = a.payload.doc.id;        //the error is here at the a.payload.doc."id"
          return { id, ...data };
        });
      })
    );
  }

Any help is greatly appreciated. Thank you!

Edit: SOLUTION FOUND

I finally got it working, turns out there was some issue with the @angular/fire installation. All I had to do was

  1. npm install firebase
  2. npm install @angular/fire
  3. ng add @angular/fire
  4. finally run npm install again

And the code worked just fine. Evidently, some issues caused dependencies on package.json not to be properly updated.

Found the solution from:1


Solution

  • The variable you are using does not have ".id" because its type is 'QueryDocumentSnapshot'.

    If you are getting this error on compilation time;

    One solution is fixing the packages / dependencies and making sure all types are as expected.

    npm install firebase @angular/fire
    ng add @angular/fire
    

    Another solution is informing your linter / compiler about the type differences.

    The following example forces the type to 'any' which can have '.payload.doc.id'.

    this.todosCollection = db.collection<Todo>("todos");
    
    this.todos = this.todosCollection.snapshotChanges().pipe(
      map((actions) => {
        return actions.map((a: any) => {
          const data = a.payload.doc.data();
          const id = a.payload.doc.id;
          return { id, ...data };
        });
      })
    );
    

    If you are getting this error on the run time you need to first fix the compilation error then make sure the '.id' property exists.