如何获取我查询的文档的ID?

时间:2018-09-19 07:05:17

标签: angular google-cloud-firestore angularfire2

我的目标是让学生通过输入提供给他们的代码来注册他的fb / google帐户。

我如何构造数据

registration-code{
  docId: {
    code:'52400028'
  }
}

provider.ts

  checkIfRegistrationCodeExists(userTypedCode:string){
    this.registrationCodeCollectionRef = this.afDb.collection('registration-code', 
    ref => ref.where('code', '==', userTypedCode));
    this.registrationCodeCollection = this.registrationCodeCollectionRef.valueChanges();
  }

然后我检查它是否匹配

  checkIfRegistrationCodeExists(){
    console.log(this.userTypedCode);

registrationCode.ts

this.registrationCodeProvider.checkIfRegistrationCodeExists(this.userTypedCode);
this.registrationCodeProvider.registrationCodeCollection.subscribe(code => {
      if(code.length = 1){
        console.log('Matched')
      } else {
        console.log('No matches');
      }
    })
  }

现在我的问题是,如何获得所讨论文档的文档ID?

有关如何执行此操作的任何提示?谢谢!

1 个答案:

答案 0 :(得分:0)

对不起,嘿。我只需要使用snapshotChanges方法,因为我仍在获取集合。

  checkIfRegistrationCodeExists(userTypedCode:string){
    this.registrationCodeCollectionRef = this.afDb.collection('registration-code', 
    ref => ref.where('code', '==', userTypedCode));
    this.registrationCodeCollection = this.registrationCodeCollectionRef.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data() as RegistrationCode;
        const id = a.payload.doc.id;
        return { id, ...data };
      })), 
    );
    return this.registrationCodeCollection;
  }

然后我这样做是为了获取ID

  checkIfRegistrationCodeExists(){
    console.log(this.userTypedCode);
    this.registrationCodeProvider.checkIfRegistrationCodeExists(this.userTypedCode);
    this.registrationCodeProvider.registrationCodeCollection.subscribe(code => {
      if(code.length = 1){
        console.log('Matched', code[0].id);
      } else {
        console.log('No matches');
      }
    })
  }
相关问题