2

Hello guys i've been trying to convert this code into modular firebase 9:

fb8: const userRef = db.collection('Users').doc();

to fb9: const userRef = doc(db, 'Users');

But i'm getting this error: FirebaseError: Invalid document reference. Document references must have an even number of segments, but Users has 1.

Please help!

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84

2 Answers2

3

The doc() method is equivalent to .collection('users').doc('docID') where you need to specify the ID. If you are trying to add a document with random ID then you add use addDoc() with collection() as shown below:

const usersCol = collection(db, 'Users')

await addDoc(usersCol, {...data})

If you want the random ID before adding the document then you can try this:

const userRef = doc(collection(db, 'Users'));
console.log(userRef.id)

Document references must have an even number of segments, but Users has 1.

You can checkout this answer for explanation of doc() and collection():

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

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
1

Expanding @Dharmaraj answer:

  • Get a docRef with a random id
  • Use the id before the document creation, for example, insert the id in the document data
  • Then create the document
const usersRef = collection(db,'users') // collectionRef
const userRef = doc(usersRef) // docRef
const id = userRef.id // a docRef has an id property
const userData = {id, ...} // insert the id among the data
await setDoc(userRef,userData) // create the document
Antoine Weber
  • 1,741
  • 1
  • 14
  • 14