Genrate doc id in firestore v9 before the doc is created

In firestore v8 (web sdk) I was doing it like below:

firestore.ref().collection("genId").doc().id

But I can’t figure out the correct syntax for v9 as collection doesn’t have doc() method anymore.

Any suggestions are much appreciated

Answer

From the Firebase documentation on adding a document:

In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call doc():

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

// Add a new document with a generated id
const newCityRef = doc(collection(db, "cities"));

// later...
await setDoc(newCityRef, data);

Instead of writing to the ref as the sample does, you can also get the ID from the document ref with:

console.log(newCityRef.id);