Search code examples
angulartypescriptfirebasegoogle-cloud-firestoreangularfire

Getting "Invalid doc ref. Doc ref must have an even number of segments," Error when writing batch doc to Firebase Firestore V9 Angularfire


I tried using writeBatch() to write documents in subcollections.

I followed the Fireabase Documentation and came up with the script:

const batch = writeBatch(this.db);

const ref = doc(this.db, 'collection/document/collection1/document/collection2');

batch.set(ref, data);

await batch.commit()

"ERROR Error: Uncaught (in promise): FirebaseError: [code=invalid-argument]: Invalid document reference. Document references must have an even number of segments, but collection/document/collection1/document/collection2 has 5."

I read in one post that The path to a document has an even number of segments. While the path to a collection has odd. So, I decided to try using collection instead.

const batch = writeBatch(this.db);

const ref = collection(this.db, 'collection/document/collection1/document/collection2');

batch.set(ref, data);

await batch.commit()

but this time, there is a type error:

"Argument of type 'CollectionReference' is not assignable to parameter of type 'DocumentReference'. Types of property 'type' are incompatible."


Solution

  • After some searching, I found a solution in the Firebase documentation that you can create a document reference with an auto-generated ID, then use the reference later. Like so:

    const batch = writeBatch(this.db);
    
    const ref = collection(this.db, 'collection/document/collection1/document/collection2');
    
    batch.set(doc(ref), data);
    
    await batch.commit()