【问题标题】:How can I access the auto-created document ID when creating a new Firestore document in Angular?在 Angular 中创建新的 Firestore 文档时,如何访问自动创建的文档 ID?
【发布时间】:2020-03-03 09:33:44
【问题描述】:

我试图在创建文档时返回文档 ID。由于 Firebase 函数是异步的,因此在查询完成之前返回值不会完成。如何防止这种情况发生,以便在查询完成后等待获取值?

这个函数创建文件位于一个服务中:

public makeDoc(title: string, score: number): any{

    const fields = {
      title: title,
      score: number
    }

   this.db.collection('saved').add(fields)
   .then(function(ref) {
     console.log(ref.id);
     return ref.id;
     })

  }

我从位于组件中的函数调用它:

onCreate() {
      const str = this.createService.makeDoc(this.title, this.score);
    console.log(str);

}

【问题讨论】:

标签: javascript angular firebase async-await google-cloud-firestore


【解决方案1】:

尝试以下操作:

const fields = {
      title: title,
      score: number
    }


  var newFieldsRef = this.db.collection('saved').push();
  this.db.collection('saved').child(newFieldsRef).set(fields);

  var id = newFieldsRef.toString();

【讨论】:

  • 它返回一个错误 -> 属性 'push' 在类型 'AngularFirestoreCollection' 上不存在
  • @ManWeb 你是怎么定义db的?
  • @MichailKozlova 我已经提炼为 -> 私人数据库:AngularFirestore
  • @ManWeb 好的,抱歉,与 Firebase 数据库混淆了,Firestore 确实没有 push() 功能
【解决方案2】:

您不想阻止等到查询完成,您应该在此使用 Promise。

首先,如果您还没有,请确保在服务中导入 firestore 命名空间:

import { firestore } from 'firebase';

现在,为您服务:

我不得不稍微更改您的 makeDoc 方法,因为 fields 对象没有以有效的方式创建(例如重用 number 类型):

public makeDoc(titleParam: string, scoreParam: number): Promise<firestore.DocumentReference> {
  const fields = {
    title: titleParam,
    score: scoreParam
  };

  return this.db.collection('saved').add(fields);
}

现在返回一个Promise&lt;DocumentReference&gt;,解析后,引用将指向创建的文档。

现在,在 onCreate 中对它的调用如下所示:

onCreate() {
  this.createService.makeDoc('myTitle', 123)
    .then((ref) => { console.log(ref.id); })
    .catch((err) => { console.log(err); });
}

这将在 id 可用时立即记录它。

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    相关资源
    最近更新 更多