The document reference is not valid. It must have an equal number of segments, but the reference cities/SF/landmarks has 3 segments

Hello! I am currently learning from the firestore tutorial

Initially, they guide me to populate the database with the following data:

    import { collection, doc, setDoc } from "firebase/firestore"; 

    const citiesRef = collection(db, "cities");

    await setDoc(doc(citiesRef, "SF"), {
        name: "San Francisco", state: "CA", country: "USA",
        capital: false, population: 860000,
        regions: ["west_coast", "norcal"] });
    // other city data...

Later in the tutorial, there is a step to create sub-collections using the code provided below:

    import { collection, doc, setDoc } from "firebase/firestore";  

    const citiesRef = collection(db, 'cities');

    await Promise.all([
        setDoc(doc(citiesRef, 'SF', 'landmarks'), {
            name: 'Golden Gate Bridge',
            type: 'bridge'
        }),
        // other landmark data...
    ]); 

However, the above code snippet leads to an error message stating:

errors.ts:94 Uncaught FirebaseError: Invalid document reference. Document references must have an even number of segments, but cities/SF/landmarks has 3.

If anyone knows why this error is occurring, please let me know!

Answer №1

It seems there was an error in the code sample provided. As citiesRef is a collection reference,

doc(citiesRef, 'SF', 'landmarks')
is also a collection reference, and you cannot use setDoc on a collection reference.

To resolve this issue, you should use addDoc instead of setDoc, and replace doc with collection. Making these changes will improve the functionality:

addDoc(collection(citiesRef, 'SF', 'landmarks'), {
    name: 'Golden Gate Bridge',
    type: 'bridge'
}),

Last updated on June 16, 2022: The documentation has been corrected to use addDoc() instead of setDoc(), and collection() instead of doc().

Answer №2

After facing the same issue and undergoing numerous trials, I finally found a solution that I felt compelled to share: The problem stems from incorrect document references when working with Firebase. It is crucial to follow the pattern of collection/document/collection/document for proper functioning. In my case, mistakenly referencing collection/document/document led to this error.

Here is an example of the wrong way:

setDoc(doc(db, "collectionName", userID, documentID), ...

Corrected approach (adding another collection in between):

setDoc(doc(db, "collectionName", userID, "anotherCollectionName", documentID), ...

Answer №3

[addDoc]([collection](citiesRef, 'DC', 'landmarks'), {
    name: 'National Air and Space Museum',
    type: 'museum'
}),

Modify your addDoc method to replace setDoc and use collection instead of doc when referencing a collection.

Answer №4

I encountered a similar issue, however, I preferred using the setDoc over addDoc.

The error message indicated an invalid document reference due to an odd number of segments in the collection path.

The root cause of my problem was calling doc(db, 'collection', id) with an empty string as the id.

To address this, I implemented a check to ensure that the collectionId is neither undefined nor an empty string.

Below is the modified code snippet:

export const addPlayedGame = async (collectionId: string) => {
  try {
    if (!collectionId) return false;

    const collectionRef = doc(firebase.db, 'collection', collectionId);

    const updateObject = {
     ...
    };

    await setDoc(collectionRef, updateObject, { merge: true });

    return true;
  } catch (error) {
    return false;
  }
};

Answer №5

The conversation has been ongoing for quite some time, but I understand the issue at hand and no one has provided the correct solution yet, so here is my input. The problem lies with the "doc()" function which requires two arguments: the first argument being the collection reference (for example: collection(db, "i am a collection")), and the second argument being the id of the document you wish to retrieve.

For instance:

let firestore = getFirestore();

let colref = collection(firestore, "i am a collection");

let document = doc(colref, "id of the document");

Therefore, in your case, the "doc()" function already receives the collection name from your "citiesRef" variable. You should only include 2 arguments unless you intend to pass the "citiesRef" arguments into the "doc()" function's arguments.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging async/await in express

I am encountering an issue with my app.post method while trying to deploy on Firebase. The error message reads: Parsing error: Unexpected token =>. I am fairly new to node.js and Javascript as I primarily work with Swift. However, I require this code fo ...

Leveraging the power of the map function to manipulate data retrieved

I am working on a nextjs app that uses typescript and a Strapi backend with graphql. My goal is to fetch the graphql data from strapi and display it in the react app, specifically a list of font names. In my react code, I have a query that works in the p ...

Tips for preventing a wrapped union type from collapsing

It seems like there is an issue with Typescript collapsing a wrapped union type when it knows the initial value, which is not what I want. I'm uncertain if this is a bug or intended behavior, so I'm curious if there's a way to work around it ...

JavaScript: Organizing values based on their case sensitivity

Imagine a scenario where we have models ABC23x, ABC23X & abc23X all referring to the same model. These model names are retrieved from API endpoints. Now the UI has two tasks: Display only one model name (ABC23X) When calling the REST API, we need to sen ...

Type error encountered in TypeScript when using React Hotkeys keymap

I'm currently following the instructions provided in the documentation. const keyMap = { CONTRACT: "alt+down", COMMAND_DOWN: { sequence: "command", action: "keydown" } }; An error is occurring and I'm unsure ...

Converting Angular object into an array

Is there a way to extract only the data array from the observable response? I'm interested in retrieving the values of cat_id, cat_name, and cat_description, but not the sql_types array. { "code": 0, "message": "" ...

What is the proper way to declare and utilize a constant list within a component template in NuxtJs?

Can someone help me with using itemList in a template? The itemlist is a static list, but I am unsure of where to declare it and how to export it to the template. <template> <table class="table table is-striped is-narrow is-fullwidth" ...

Angular4 Blueprint

Here is a simple demonstration of ngTemplate that I have coded: <div> <ng-container [ngTemplateOutlet] ="template1"> </ng-container></div> Below are the template examples: <ng-template #template1> This is the 1st template & ...

What is the reasoning behind TypeScript's acceptance of value as a data type?

What is the reason for TypeScript supporting value as a data type? The following scenarios demonstrate both acceptable and unacceptable declarations. export class MyComponent{ error: 'test' = 'test'; // accept error: & ...

Issue with Angular 8: discrepancy between the value utilized in component.html and the value stored in component.ts (Azure application service)

Encountering a peculiar behavior in one of my Angular applications. In the component.html file, I aim to display "UAT" and style the Angular mat elements with a vibrant orange color when in UAT mode, while displaying them in blue without any mention of UAT ...

Guide to implementing validation on submit in Angular 7 reactive forms

Code Snippet: handleFormSubmission(){ if(this.Registration.invalid){ return; } alert('Thank you for submitting! Data:' + JSON.stringify(this.Registration.value)); } Form Markup: <form class="admin-form" [formGroup]="Registration" (ng ...

Issue encountered when trying to access colors within MUI theme in Typescript

I have a unique color scheme set for my material ui theme, which I define as follows: createTheme({ palette: { primary: { main: '#193C7D', dark: '#112853', light: '#2C4DBC', '900': &apo ...

It has come to our attention that one or more of your Android applications share a SHA-1 fingerprint and package name combination that is already being utilized

https://i.sstatic.net/0drBb.png We originally had our application set up on an old Firebase project, but now we have migrated to a new Firebase project for the same application. In the old Firebase project, there was one specific SHA key that was being us ...

Managing dynamic paths using Next.JS on Firebase (server-side)

I've encountered a problem with dynamic routes. Here is the file structure I'm working with: app members [memberID] page.tsx When I run: % npm run dev And visit this URL in my browser: http://localhost:3000/members/AA66 ...

When importing a React Component with styling into the pages folder, it fails to function properly

I created a component in my components directory with custom styling: // import Link from "next/link"; import {Link} from "react-scroll" export default function Navbar() { return ( <div className="fixed w-full h-[79px] fle ...

Why does `react/require-default-props` still display an error even when a default prop value has been set?

This inquiry pertains to the guideline require-default-props. Here is the code snippet in question: function MyComponent({ blubb = 'my default', }: { blubb?: string, }) { // blubb defaults to 'my default' }; Eslint is flagging a ...

Tips for creating the overload of a function that accepts a class as a parameter

My map is packed with various types of values (strings, objects, etc.) assigned to different types of keys (strings, classes, etc.). Whenever the key is a class, the corresponding value is always an instance of that class. I attempted to create a functio ...

Retrieve information before rendering a component in Reactjs

I am currently experiencing a minor issue with my react code. I need the data to be fully fetched before rendering, but despite trying different methods like setting 'groupLoaded' to true after the async call, it still isn't functioning as e ...

A volume slide will decrease to zero if the 'mute' button is selected

Well, the title pretty much sums it up. I successfully managed to make it so that when you slide the volume to 0, it mutes the video. However, I am struggling with achieving this: if the video is muted, the volume slider should automatically move to 0. I ...

Mastering the art of using Styled() with MUI V5

Having trouble utilizing MUI Styled () on a larger scale. Can someone please review the code we used in previous versions and advise how to replicate it in MUI V5? Previous Method: const useStyles = makeStyles((theme) => ({ root: { backgroundColo ...