mayank3503
mayank3503

Reputation: 367

Store documentId as field in document

I want to store the documentId created in collection as the field/property as docid in the same document. I am using cloud firestore.

It is showing error "ReferenceError: doc is not defined" whenever I try and store the doc.id

db.collection("Colleges").doc(user.uid).collection('Internships').doc().set({

          CompanyName :this.I_company,
            InternshipTitle : this.I_title,

            duration: this.duration,
            amount:this.I_amount,
            week:this.week,
            docid: doc.id
})

Upvotes: 1

Views: 134

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

Indeed, a call to the doc() method of a CollectionReference without any path will return a DocumentReference with "an automatically-generated unique ID".

But you have to do as follows: first get the new DocumentReference, then use the set() method on this DocumentReference.

var docRef = db.collection("Colleges").doc(user.uid).collection('Internships').doc();

docRef.set({

          CompanyName :this.I_company,
            InternshipTitle : this.I_title,

            duration: this.duration,
            amount:this.I_amount,
            week:this.week,
            docid: docRef.id
})

However, you may double check if you really need to write the docRef.id in a specific field of the document, because in any case you can get it later with the id property.

Upvotes: 1

Related Questions