Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get a DocumentReference without providing an ID in Firebase 9 web version Javascript SDK

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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}`);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading