I'm trying to commit a batch write using firebase 9 modular sdk. This operation includes creating a post document, ideally with an auto generated id.
const batch = writeBatch(db)
const postRef = doc(db, 'posts') // this fails, must pass and id
const threadRef = doc(db, 'threads', post.threadId)
batch.set(postRef, post)
batch.update(threadRef,
'posts', arrayUnion(postRef.id),
'contributors', arrayUnion(state.authId))
await batch.commit()
In Firebase 8 it's possible to obtain a document reference with a random generated id using with the following code.
firebase.firestore().collection(nameOfTheCollection).doc()
I'm trying to accomplish the same thing using Firebase 9 modular sdk, but I can't find any method to do this. Is it possible to get a document reference with a random generated id without creating the document first with Firebase 9?
CodePudding user response:
You can use the doc()
function and pass a CollectionReference
as first parameter without any path segments as shown below:
import { doc, collection } from "firebase/firestore";
const docRef = doc(collection(db, "colName")); // Don't specify an ID yourself
console.log(`New Document ID: ${docRef.id}`);