Firestore v9 Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore

Viewed 1359

I tried to add new users from the signup page to firestore but it didn't work.

Here's my config.js

import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getDatabase } from "firebase/database";

const firebaseConfig = initializeApp ({
  //cred
});

export const auth = getAuth(firebaseConfig)
export const database = getDatabase(firebaseConfig);

And Signup.js

import React, { Component } from "react";
import  firebase  from "./config";
import { collection, addDoc,doc } from "firebase/firestore"; 

class Signup extends Component {

    constructor(props) {
        super(props);
        this.state = {
            name: '-',
            email: '-',
        };
    }

    addUser = e => {
        e.preventDefault();

        try {
            const collectionRef = doc(database, 'users');
            const docRef = addDoc(collectionRef, {
                name: this.state.name,
                email: this.state.email,
            });
          } catch (e) {
            console.error("Error adding document: ", e);
          }

    render(){
        return (
            <div>
              //do something
              <button className="btn btn-primary" onClick={this.addUser}>Submit</button>
            </div>
    )}
}

And here's the error:

FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore

I changed Config.js to:

export const auth = getAuth()
export const database = getDatabase();

and I still got the same error. Does it mean that I didn't connect firestore successfully? :'( Please help me solve this problem. Thank you.

2 Answers
const collectionRef = doc(database, 'users');

The database here is an instance of realtime database and not Firestore.

export const database = getFirestore(); // not getDatabase()

You must use getFirestore() to get an instance of Firestore and pass it in doc(). The error says Expected first argument to collection() even if an invalid argument is passed to doc().

Try changing the path for the collection

const collectionRef = doc(database, '/users');

it worked with me!

Related