2

I'm inserting a new document into my firestore collection like so:

this.afs.collection<Client>('clients').add(this.form.value).then(docRef => {
  console.log("Need to output the firestore generated doc id of the document here: ...")
})

3 Answers 3

4

Try

this.afs.collection<Client>('clients').add(this.form.value).then(docRef => {
  console.log(docRef.id);
})
2
  • This yields a compile error: Property 'id' does not exist on type 'void | DocumentReference'. Property 'id' does not exist on type 'void'. Commented Apr 10, 2018 at 7:02
  • 1
    Works for me. Thanks. Commented Nov 1, 2019 at 19:30
4

Got it: then() takes a union type (http://www.typescriptlang.org/docs/handbook/advanced-types.html): void | DocumentReference.

Therefore needs to be addressed like this:

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

You can generate a key by yourself.

...
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
  • Thanks, but that does not answer the OP. Commented Apr 9, 2018 at 11:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.