Home > Net >  db.collection is not a function firebase firestore
db.collection is not a function firebase firestore

Time:10-18

Hello I am trying to configure react app with firebase and use firestore.

"firebase": "^9.1.3"

I followed the instructions given in official docs.

Here is my congig.js file.

import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';

const firebaseConfig = {
    apiKey: '****',    
    authDomain: '*****',    
    projectId: '*****',    
    storageBucket: '*****',    
    messagingSenderId: '****',    
    appId: '*****',
};

const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);

I am sure this gets initialized.

When I export it and use it in other file. collection is greyed out in vs code that means i am not using the import.

databaseservice.js

import { db } from './config';
import { collection, doc } from 'firebase/firestore';

export const getChapters = (scanId) => {
    db.collection('somecollection')
        .doc(scanId)
        .get()
        .then((doc) => {
            if (doc.exists) {
                console.log('Document data:', doc.data());
            } else {
                // doc.data() will be undefined in this case
                console.log('No such document!');
            }
        })
        .catch((error) => {
            console.log('Error getting document:', error);
        });
};

Error:TypeError: config__WEBPACK_IMPORTED_MODULE_0_.db.collection is not a function

I have tried with compat and lite versions. Getting the same issue.

CodePudding user response:

This is v8/compat syntax:

db.collection('somecollection')
    .doc(scanId)
    .get()
    .then((doc) => {

In v9/modular syntax, the equivalent is:

getDoc(doc(db, 'somecollection', scanId))
    .then((doc) => {

For converting this type of thing, I find it easiest to keep the Firebase documentation and upgrade guide handy.

CodePudding user response:

Firebase have changed their API to new modular syntax in version 9. You are using old syntax from version 8. You can read more about this and find instructions on upgrading your code here: https://firebase.google.com/docs/web/modular-upgrade

Also, everywhere in Firebase documentation, they now have 2 separate examples: one for old syntax, one or new modular syntax: https://firebase.google.com/docs/firestore/query-data/get-data

  • Related