1

I am trying to add a new document in a firestore transaction with version 9 of the Firebase JS SDK. In version 8, we can use

const newDocRef = db.collection('coll').doc();

to get a DocumentReference to a document that does not exist yet, and then do a

transaction.set(newDocRef, { ... });

to set the document in a transaction. How would we do the same in version 9? The new CollectionReference class does not seem have a doc() method as in version 8. Thanks!

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
Ping
  • 361
  • 1
  • 2
  • 5
  • 2
    Does this answer your question? [Genrate doc id in firestore v9 before the doc is created](https://stackoverflow.com/questions/69859073/genrate-doc-id-in-firestore-v9-before-the-doc-is-created) – Jose German Perez Sanchez Jan 20 '22 at 22:12

2 Answers2

0

There's a function doc() to create a DocumentReference and then runTransaction() to run a transaction. Try refactoring the code like this:

import { getFirestore, doc, runTransaction } from "firebase/firestore"

const newDocRef = doc(db, "col_name", "doc_id");

await runTransaction(db, async (transaction) => {
  // ...
  transaction.set(newDocRef, { ...data });
});

The documentation has examples with both the name-spaced and functional syntax. Also checkout this answer for better explanation of syntax differences in V8 and V9:

Firestore: What's the pattern for adding new data in Web v9?

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • Thanks, but I do not want to specify my own "doc_id". If it is outside of a transaction, I would use [addDoc](https://firebase.google.com/docs/reference/js/firestore_.md#adddoc), but I need to do this in a transaction. – Ping Jan 20 '22 at 19:11
  • @Ping can you try `const newDocRef = doc(db, "col_name")` without doc ID? – Dharmaraj Jan 20 '22 at 19:22
  • Then I get `FirebaseError: Invalid document reference. Document references must have an even number of segments ...`. – Ping Jan 20 '22 at 21:13
0

Found the answer here. This works for me:

const newDocRef = doc(collection(db, "coll"));

transaction.set(newDocRef, { ... });
Ping
  • 361
  • 1
  • 2
  • 5