Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fix "FirebaseError: Type does not match the expected instance." on firebase transaction. React.js

on my site, when a section is deleted I want all items in that section removed so I am using a transaction

        const sectionRef = db
            .collection('items')
            .where('subSection', '==', sectionName);

        db.runTransaction((transaction) => {
            return transaction
                .get(sectionRef)
                .then((data) => {                   
                    data.docs.map((doc) => {                        
                        transaction.delete(doc);
                    });
                })
                .catch((e) => {
                    console.log('transaction failed', e);
                });
        });
    };

i am getting the following error

(FirebaseError): Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?

here is the firebase config

firebaseConfig = {
        apiKey: process.env.REACT_APP_PROD_API_KEY,
        authDomain: process.env.REACT_APP_PROD_AUTH_DOMAIN,
        projectId: process.env.REACT_APP_PROD_PROJECT_ID,
        storageBucket: process.env.REACT_APP_PROD_STORAGE_BUCKET,
        messagingSenderId: process.env.REACT_APP_PROD_MESSAGING_SENDER_ID,
        appId: process.env.REACT_APP_PROD_APP_ID,
        measurementId: process.env.REACT_APP_PROD_MEASUREMENT_ID,
    };
    const firebaseApp = firebase.initializeApp(firebaseConfig);
    const db = firebaseApp.firestore();

can anyone see the issue?

like image 244
jaggysnake Avatar asked Oct 29 '25 00:10

jaggysnake


1 Answers

With the JS SDK (and the other client SDKs: iOS, Android, C++) you cannot get the docs of a collection (or of a query) in a Transaction.

As you will see in the doc, you need to pass a DocumentReference to the get() method (of a Transaction).

You can call this get() method several times in the transaction, but you cannot pass a CollectionReference to it.


On the other hand, this is possible via the Admin SDKs (i.e. the server libraries). For example, with the Node.js one, see the doc for the get() method.

You can get more details about the difference between these SDKs, and their reasons, in this documentation item.


So, since you use a query it means that you don't now upfront (i.e. when coding) the list of the documents to read in the Transaction. So you should use the Admin SDK, for example in a Cloud Function.

like image 149
Renaud Tarnec Avatar answered Oct 30 '25 15:10

Renaud Tarnec