wick3d
wick3d

Reputation: 1392

db.collection is not a function firebase firestore

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.

Upvotes: 0

Views: 435

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

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.

Upvotes: 2

Maksym Shcherban
Maksym Shcherban

Reputation: 783

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

Upvotes: 0

Related Questions