Include the document id as a field id in firestore

Solution 1:

See JS SDK v9 syntax at the bottom

There is a simpler way to achieve that, using the doc() method, as follows (here with the JavaScript SDK v8)

var newDocRef = db.collection('collectionname').doc();
newDocRef.set({
                 name:'Jhon Doe',
                 job:'Programmer',
                 id: newDocRef.id
          })

As explained in the doc:

(the doc() method) gets a DocumentReference for the document within the collection at the specified path. If no path is specified, an automatically-generated unique ID will be used for the returned DocumentReference.


You will find similar methods in the other Client SDKs, here for Android and here for iOS.


UPDATE FOR JS SDK v9:

import { collection, doc, setDoc } from "firebase/firestore"; 

const newDocRef = doc(collection(db, "collectionname"));
await setDoc(
       newDocRef, 
       {
         name:'Jhon Doe',
         job:'Programmer',
         id: newDocRef.id
       }
   )