如何检索刚刚插入的firestore文档的id(使用angularfire2)?

时间:2018-04-09 08:58:57

标签: angular5 google-cloud-firestore angularfire2

我将新文档插入我的firestore集合中,如下所示:

var dataPoints = from e in evaluations.Take(20)
                  group e.EvaluationID by e.description into g
                  select new DataPoint { Count = g.Count(), Profession = g.Key};

3 个答案:

答案 0 :(得分:2)

您可以自己生成密钥。

...
this.generatedKey = this.generateNewKey('clients');
...

this.afs.collection<Client>(`clients`).doc(this.generatedKey)
  .set({ someField: 'some value' })
  .then(docRef => {
    console.log("Self generated doc ID: ...", this.generatedKey )
})

generateNewKey(ref: any) {
  const _ref = firebase.firestore().collection(ref).doc();
  const newKey = _ref.id;
  return newKey;
}

答案 1 :(得分:0)

尝试

this.afs.collection<Client>('clients').add(this.form.value).then(docRef => {
  console.log(docRef.id);
})

答案 2 :(得分:0)

得到它:then()采用联合类型http://www.typescriptlang.org/docs/handbook/advanced-types.html):void | DocumentReference

因此需要像这样解决:

this.afs.collection<Client>('clients').add(this.form.value).then(docRef => {
  console.log((docRef) ? (<DocumentReference>docRef).id : 'void') // docRef of type void | DocumentReference
})