How can we create a document with a custom id in firestore with the new modular SDK V9?
const register = async function (adminEmail){
try{
const docSnap = await getDoc(availableIdRef);
const collegeId = docSnap.data().id; //This should be the document id
const adminRef = collection(firestore, 'admin');
await addDoc(adminRef, {adminEmail, collegeId});
}catch(e){
alert("Error!");
}
}
I want to create a new document with id as collegeId in admin collection.
I know how to do this in web version 8(namespaced) but have no idea about web version 9(modular).
You can use setDoc() method to specify an ID instead of addDoc which will generates a random ID as mentioned in the documentation:
const adminRef = doc(firestore, 'admin', collegeId);
// doc --->^
await setDoc(adminRef, {email: adminEmail, id: collegeId}) // overwrites the doc if it already exists
// ^^^
Also note that to create a DocumentReference you need to use doc() and not collection() which is used to create a CollectionReference. I've explained difference in these 2 here: Firestore: What's the pattern for adding new data in Web v9?