0

I have created a firestore collection and am able to add data(documents) to it, and firestore automatically generates its document id.

Adding data

this.afs.collection('questions').add({ 'question': message, 'asker': this.currentStudent, 'upvotes': this.upvote, 'lesson': this.currentLesson });

I would like to get the document id of this newly added document and assign it to a variable, something like:

this.documentId = newlyGeneratedDocumentsId

I read somewhere that I can do this using the document.Set() method, if so, how may I go about doing this?

cosmo
  • 751
  • 2
  • 14
  • 42

1 Answers1

1

The add() methods returns a promise. When that promise resolves, it gives you the DocumentReference of the new document.

So you can get it with:

this.afs.collection('questions')
    .add({ 'question': message, 'asker': this.currentStudent, 'upvotes': this.upvote, 'lesson': this.currentLesson })
    .then(function(documentRef) {
        documentId = documentRef.id;
    });

Also see my answer here: Firebase: Get document snapshot after creating

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • This worked, but I am unable to assign it to a variable. I assigned it using `this.docId = documentRef.id`, and then when I console.logged `this.docId`, it returned undefined, however console logging documentRef.id returns the id. – cosmo Jan 29 '18 at 15:40
  • There are two causes of that. 1) `this` inside the callback has a different meaning than outside of it. See https://stackoverflow.com/q/20279484. 2) the code in the callback runs before the code after it, so you can only access the value *inside* the callback. See https://stackoverflow.com/q/23667086 and https://stackoverflow.com/q/14220321. – Frank van Puffelen Jan 29 '18 at 16:09