Home > Software engineering >  How do I add a document reference with an auto generated ID when writing a batch in Firebase?
How do I add a document reference with an auto generated ID when writing a batch in Firebase?

Time:02-10

When doing normal transactions in Firebase you can just use the .add function to add a new document with an auto generated ID; however, when doing a batch write with Web version 9 of the API I cannot find any documentation on how to add a new document with a auto generated ID. Currently I have the following code which is not working:

let ref = doc(db, "projects", doc())
batch.add(ref, element);
await batch.commit();

This throws the error "Function doc() cannot be called with an empty path.". In Web version 8 this worked apparently by just calling .doc(). How does one accomplish this?

CodePudding user response:

This is what worked for me:

let ref = doc(collection(db, "projects"))

CodePudding user response:

According to 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);

So it seems you'll need:

let ref = doc(db, collection("projects"))
  • Related