Anjo Bautista Liwanag
Anjo Bautista Liwanag

Reputation: 129

Firebase query `TypeError` using `firestore.FieldPath.documentId()`

My Firestore data structure looks like this:

enter image description here

db.firestore.FieldPath.documentId(), '==', '20210106.0' does not work, but I am not sure why. I need to read it as a float, so I can use => or =< as Start Date and End Date in my query.

In the console I get this error message: TypeError: Cannot read property 'FieldPath' of undefined'

Here is my code:

actions: {
    getFireBaseOrders(state){
        db.collection(`ordersOptimized`).where(
            db.firestore.FieldPath.documentId(),
            '==',
            '20210106.0').onSnapshot((res) => {
                const changes = res.docChanges();
                changes.forEach((change) => {
                    if (change.type === "added") {
                        let payload = change.doc.data();
                        state.commit("firebaseOrders", payload);
                    }
                });
            });
    },

What am I missing? How do I make the condition work?

Upvotes: 0

Views: 956

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83103

If you want to listen to changes occuring to the Firestore document with ID 20210106.0, just do as follows:

db.collection("ordersOptimized").doc("20210106.0").get()
   .onSnapshot(function(doc) {
        // ....
        // Based on your database screenshot you should loop over the 
        // JavaScript object returned by doc.data()
        // Something like

        for (const [key, value] of Object.entries(doc.data())) {
            console.log(`${key}: ${value}`);
        }

        // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
    });

Since 20210106.0 is the ID of a document in the ordersOptimizedcollection, only one document with this ID can exist in this collection. Therefore you should not use a Query (i.e. db.collection('...').where('...')) in order to listen to changes to this document.


On this other hand, if you want to listen to ALL the documents of the ordersOptimized collection, see the corresponding doc.

Upvotes: 1

Related Questions