Skip to main content

Fix Firestore Error: A Document Must Have an Even Number of Path Elements

Β· 5 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

If you are working with Firebase and suddenly see the error fatal: A document must have an even number of path elements, don't worry-you haven't broken your database. This is Firestore's way of telling you that you've gotten lost in the "Map" of your data.

In Firestore, there is one unbreakable rule: Collections and Documents must always alternate.


πŸ—οΈ The Rule of the "Firestore Sandwich"​

Think of your database like a file system, but with a very strict pattern. You can never have a collection inside a collection, and you can never have a document directly inside a document. It must always be: Collection β†’ Document β†’ Collection β†’ Document

Counting the "Path Elements"​

Every time you add a name to your path, you are adding an "element."

  • Odd Numbers (1, 3, 5...) always point to a Collection.
  • Even Numbers (2, 4, 6...) always point to a Document.

If you try to use a function meant for a Document (like .doc() or .update()) but provide an Odd number of path segments, Firestore throws this error because you are technically pointing at an entire folder, not a specific file.


πŸ’» The "Wrong vs. Right" Code​

This error usually happens when you forget to include a specific Unique ID (UID) at the end of your string.

The Wrong Way (Odd Path)​

// This path has 3 elements: users (1) / 12345 (2) / posts (3)
// "posts" is a COLLECTION. You cannot "set" data to a folder!
db.doc("users/12345/posts").set({ title: "Hello" });
// ❌ Error: A document must have an even number of path elements

The Right Way (Even Path)​

// This path has 4 elements: users (1) / 12345 (2) / posts (3) / post_abc (4)
// "post_abc" is a DOCUMENT. This works!
db.doc("users/12345/posts/post_abc").set({ title: "Hello" });
// βœ… Success!


πŸ“Š The Path Cheat Sheet​

Path ElementsPoints To...Example Path
1 (Odd)Collectionusers
2 (Even)Documentusers/john_doe
3 (Odd)Sub-Collectionusers/john_doe/orders
4 (Even)Sub-Documentusers/john_doe/orders/order_99

πŸ› οΈ Common Culprits & Fixes​

1. The "Undefined" Variable​

If you are using a variable for your ID, and that variable is undefined, the path might accidentally shorten.

  • Path: "users/" + userId
  • Result if userId is missing: "users/" (1 element = Error)

2. Leading/Trailing Slashes​

Extra slashes can sometimes confuse the parser into thinking there is an empty "element" at the end.

  • Bad: db.doc("/users/123/")
  • Fix: Always trim your strings or use the .collection().doc() syntax instead of a single string path.

3. Using the Wrong Method​

If you actually want to add a new document to a collection and let Firestore generate the ID, use .add() on a Collection Reference instead of .set() on a Document Reference.


πŸ“š Sources & Technical Refs​