cosmo
cosmo

Reputation: 761

How to assign document id to a variable in firestore?

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?

Upvotes: 0

Views: 2029

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598901

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

Upvotes: 1

Related Questions