Skip to content
Advertisement

Firebase 9 – How to do new doc ref

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!

Advertisement

Answer

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?

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement