Web-BlogFieldPath in Firestore

FieldPath in Firestore

Use paths with (otherwise) invalid characters

Topics:

  • Firebase

Read Time: 2 min

Published: 2022.03.27

Last Updated: 2022.03.27

Title Image FieldPath

In this short blog I want to share a solution to a problem with you that I had with reading data from a Firestore-Database which took me some time to figure out.

The Problem

There are some characters which are not allowed to be used when querying for data in firestore. Let me start with an example. You might try to query for all documents in a collection recipes which have a field called ingredients and a sub-field fruit/vegetables set to true with the following code:

JAVASCRIPT

import { db } from "src/services/firebase/firebaseAdmin";

const results = [];
await db
    .collection("recipes")
    .where("ingredients.fruit/vegetables", "==", true)
    .get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          results.push(doc.data());
        });
    });

(db is an initialized instance of an Admin-Firestore App. See: https://firebase.google.com/docs/firestore/quickstart)

When trying to execute the code above, you will get the following error in your console:

Error: Value for argument "fieldPath" is not a valid field path. Paths can't be empty and must not contain "*~/[]".

Looks like we are not allowed to use the / in our query.
But does that mean we need to avoid the given characters in our database altogether? No.

The Solution

You can use the FieldPath constructor to create a query for the given example like this:

JAVASCRIPT

import { db } from "src/services/firebase/firebaseAdmin";
import { FieldPath } from "firebase-admin/firestore";

const results = [];
await db
    .collection("recipes")
    .where(new FieldPath("ingredients", "fruit/vegetables"), "==", true)
    .get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          results.push(doc.data());
        });
    });

The query should now work as expected.

Never miss a post again:

Feedback Me: