When i make a query to my firestore database i got this error
FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore
Apparenly i havent pass the right argument to getFirestore()
Here is my db initialization code:
import { initializeApp } from "firebase/app";
import { getFirestore, connectFirestoreEmulator } from "@firebase/firestore/lite";
class Db {
static firebaseApp = null;
constructor() {
if (!Db.firebaseApp) {
Db.firebaseApp = initializeApp({
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
});
const useEmulator = process.env.NODE_ENV === "development";
this.db = getFirestore();
if (useEmulator) {
const emulatorHost = "192.168.1.51";
const emulatorPort = 8080;
connectFirestoreEmulator(this.db, emulatorHost, emulatorPort);
}
}
}
}
export default Db;
the static property is for executing initializeApp one time at the instantation of the class and not getting this error:
FirebaseError: Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.
Here is the queries i make:
import { collection, getDocs, query, where } from "@firebase/firestore/lite";
import Db from "./DataBase.js";
class SignUpClientSide extends Db {
async checkUsernameUniqueness(username) {
const usersRef = collection(this.db, "users");
console.log(usersRef);
const lowercaseQuerySnapshot = await getDocs(query(usersRef, where("username", "==", username.toLowerCase())));
console.log(lowercaseQuerySnapshot);
const uppercaseQuerySnapshot = await getDocs(query(usersRef, where("username", "==", username.toUpperCase())));
if (!lowercaseQuerySnapshot.empty || !uppercaseQuerySnapshot.empty) {
return false;
}
return true;
}
}
2
Answers
I just update the constructor by moving
this.db = getFirestore();
out of the if statement and use directly the firestore intanceNow i'am able to make a query request to the db but i got this new error:
I thinks it s a network error. The firestore emulator is on
Inside of
SignUpClientSide
,this.db
is likely undefined because you haven’t called the parent’s constructor.In Javascript you can use the
super()
method to call the parent constructor, likely in your own constructor (ie.SignUpClientSide.constructor
), but this isn’t done automatically.See this example to learn more:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super