【问题标题】:How do I get the id of the document I queried?如何获取我查询的文档的id?
【发布时间】:2023-04-02 10:25:01
【问题描述】:

我的目标是让学生通过输入提供给他们的代码来注册他/她的 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);

注册码.ts

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

现在我的问题是,我将如何获取相关文档的文档 ID?

关于如何做到这一点的任何提示?谢谢!

【问题讨论】:

    标签: angular google-cloud-firestore angularfire2


    【解决方案1】:

    傻了,呵呵。我只需要使用 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');
          }
        })
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 2022-07-11
      • 2021-10-28
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多