Home > Net >  Firestore Query Raises Exception if Including orderBy
Firestore Query Raises Exception if Including orderBy

Time:03-25

I have the following function:

async function loadGalleryImages2() { // load images for gallery
    const collectionRef = db.collection('projects').doc(project.id).collection('images')
    const docQuery = query(collectionRef, orderBy('displayOrder'))
}

where the declaration of docQuery causes the following error to appear in console:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'startAt')

If I remove the orderBy parameter as shown below, I do not get any error.

async function loadGalleryImages2() { // load images for gallery
    const collectionRef = db.collection('projects').doc(project.id).collection('images')
    const docQuery = query(collectionRef)
}

The firebase docs show enter image description here

Moving forward, you must only choose one version between the two. Also, check this guide for more information in upgrading from version 8 to modular (version 9) Web SDK.

I've tried your code for both modular and namespaced using the code below:

For namespaced (web version 8):

async function loadGalleryImages2() { // load images for gallery
    const collectionRef = db.collection("projects").doc(project.id).collection("images").orderBy("displayOrder");
    collectionRef.get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data());
        });
    })
    .catch((error) => {
        console.log("Error getting documents: ", error);
    });
}

And for modular (web version 9):

// Add this in your import statement if you choose to use modular version
import { getFirestore, collection, query, getDocs, onSnapshot } from "firebase/firestore";

async function loadGalleryImages2() { // load images for gallery
  const querySnapshot = await getDocs(collection(db, "projects", project.id, "images"), orderBy("displayOrder"));
  querySnapshot.forEach((doc) => {
    // doc.data() is never undefined for query doc snapshots
    console.log(doc.id, " => ", doc.data());
  });
}
  • Related