updateDoc: Uncaught FirebaseError: Invalid document reference - javascript

When updating a document in v9 of firebase/firestore I got an error and I've been following the official documentation and not sure what I'm doing wrong:
import { initializeApp } from "firebase/app";
import { getFirestore, updateDoc, doc} from 'firebase/firestore';
import firebaseConfig from '../utils/firestore';
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
function updateSeries(docID, name, desc) {
const data = {
name: name,
desc: desc,
lastUpdatedAt: Timestamp.now(),
}
const seriesDocRef = doc(db, "MY_COL", docID)
return new Promise((resolve, reject) => {
updateDoc(seriesDocRef, data).then(() => {
resolve();
}).catch((e) => {
reject(e);
})
})
}
When I call this function I get this error:
errors.ts:94 Uncaught FirebaseError: Invalid document reference. Document references must have an even number of segments, but MY_COL has 1.

If the values in passed into the doc function are undefined or falsy it can cause this error. Please check if the db and docID variables are defined in:
const seriesDocRef = doc(db, "MY_COL", docID)

Related

How to use setDoc with Firebase-Admin with Typescript in firestore?

I have config/firebase.ts:
import { initializeApp, cert } from 'firebase-admin/app';
import { getFirestore } from 'firebase-admin/firestore'
const firebaseAdminApp = initializeApp({
credential: cert({
privateKey: process.env.NEXT_PUBLIC_FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
clientEmail: process.env.NEXT_PUBLIC_FIREBASE_SERVICE_EMAIL,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID
}),
databaseURL: `https://${process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID}.firebaseio.com`
});
const firestore = getFirestore(firebaseAdminApp);
export default firestore
and when trying to upsert, I have:
import firestore from "../config/firebaseAdmin";
const upsertInstance = async (instance: Instance) => {
const hashedUri = createHash('sha256').update(instance.uri).digest('hex')
const res = await firestore.doc(`instances/${hashedUri}`).set(instance);
return res
}
but I get:
Error: expected a function
What am I doing wrong?
Firebase Admin is not totally modular yet like the client SDK yet so you would have to use namespaced syntax. Admin SDK's Firestore instance won't work perfectly with client SDK functions. Try refactoring the code as shown below:
export const db = getFirestore(firebaseAdminApp);
import { db } from "../path/to/firebase"
const upsertInstance = async (instance: Instance) => {
const res = await db.doc(`instances/${instance.uri}`).set(instance);
return res;
}
Checkout the documentation for more information.

Why am I getting TypeErrors 'x' is not a function with firebase collection query?

My js file is correctly entered in the DOM, I have initailized firebase in the firebase.js file. Why am I getting a
TypeError 'collection(...).doc is not a function' -
The collection query is taken directly from the firebase docs site, I don't understand how this could be a type error.. Any ideas?
import { app } from "./firebase";
import { getFirestore, doc, collection } from "firebase/firestore";
const db = getFirestore(app);
// get data
const docRef = collection(db, 'posts').doc('ARt1ctrEjweKEd4gmgCr');
await docRef.get();
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
The doc() is top level function in Modular SDK and not a method on collection(). Try:
import { getFirestore, doc, getDoc } from "firebase/firestore";
// Creating DocumentReference
const docRef = doc(db, 'posts', 'ARt1ctrEjweKEd4gmgCr');
const docSnap = await getDoc(docRef);
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
Also checkout: Firestore: What's the pattern for adding new data in Web v9?

Firebase JS Uncaught (in promise) TypeError: doc is not a function

I'm working on a web app using firebase and encountered this error. After a few hours of debugging, I still haven't been able to understand what's wrong, I'll leave the code here for anyone who can help me figure out what its is that I'm doing wrong. Any suggestion will be really helpful, thanks!
Code:
import {
getFirestore,
addDoc,
doc,
updateDoc,
collection,
query,
where,
getDocs,
setDoc,
} from "firebase/firestore";
const app = initializeApp(firebaseConfig);
const firestore = getFirestore(app);
var files = [....]
getDocs(collection(firestore, "property")).then((querySnapshot) => {
querySnapshot.forEach((doc) => {
if (files.includes(decrypt(doc.data().fileno))) {
if (files.includes(decrypt(doc.data().fileno), 6)) {
let owner = "ABC";
const bref = doc(collection(firestore, "property"), doc.id);
updateDoc(bref,{owner:encrypt(owner)}).then(()=>{
console.log("updated")
})
} else {
let owner = "XYZ";
const bref = doc(collection(firestore, "property"), doc.id);
updateDoc(bref,{owner:encrypt(owner)}).then(()=>{
console.log("updated")
})
}
}
});
});
You have two definitions of doc in your code:
The doc function that you import from the Firestore SDK
The doc parameter that you declare in querySnapshot.forEach((doc) => {.
The second doc hides the first one, which is why you can't call the doc function anymore inside that callback.
The solution is to give the variable a different name, like docSnapshot.

Objects taken from Firebase are inaccessible after being pushed into an array through a forEach loop

I've been trying to create a chat app using react and firebase just for practice since I wanted to try out Firebase, and although I'm able to print out the array of objects that I retrieved into the console, I can't seem to access those objects directly... For example:
if I code "console.log(testArray);" this is what displays in the console, which is all good
0: {name: 'JohnDoe', profile_image: 'imaginary image URL', date: it, message: 'This is my first message to Firebase!'}
but if I try console.log(testArray[0]); it displays undefined in the console
Here's my code
import Config from './config';
import { initializeApp } from "firebase/app";
import {
getFirestore,
addDoc,
getDocs,
collection,
query,
orderBy
} from "firebase/firestore";
function App() {
const firebaseApp = initializeApp(Config);
const firestore = getFirestore();
const chat_collection = collection(firestore, "chat");
const addData = () => {
addDoc(chat_collection, {
date: new Date(),
message: document.getElementById("message").value,
name: "JohnDoe",
profile_image: "imaginary image URL"
});
}
let testArray = [];
const readData = async () => {
const chatAppQuery = query(
collection(firestore, 'chat'),
orderBy('date')
);
const chatSnapshot = await getDocs(chatAppQuery);
chatSnapshot.forEach((message) => {
testArray.push({
name: message.data().name,
profile_image: message.data().profile_image,
date: message.data().date,
message: message.data().message
});
});
}
readData();
console.log(testArray);
console.log(testArray[0]);
My first time asking for help on here, I'd deeply appreciate it!
Since readData is an async function, you need to use await (or then() to wait for it results.
So:
await readData();
// 👆
console.log(testArray);
console.log(testArray[0]);
If you're in a context where you can't use async/await, you can also use then:
readData().then(() => {
// 👆
console.log(testArray);
console.log(testArray[0]);
})

Firebase 9 (modular sdk) replacement for currentUser.updateEmail

How do we do this now:
const auth = getAuth(firebaseApp);
export async function updateUserEmail(email) {
try {
// let updatedUser = if need access
await auth.currentUser.updateEmail(email);
} catch (e) {
alert(e.message);
throw new Error();
}
}
updateEmail is no longer a method
You need to import updateEmail from the SDK this way now:
import firebase from "firebase/compat/app";
import { getAuth, onAuthStateChanged, updateEmail } from "firebase/auth";
// Initialize Firebase App
const app = firebase.initializeApp(firebaseConfig);
const auth = getAuth(app);
onAuthStateChanged(auth, (user) => {
console.log("Old Email", user.email);
updateEmail(user, "new#email.tld").then(() => {
console.log("email updated");
}).catch((e) => {
console.log(e);
});
});
Also you need to pass the user object itself in the updateEmail function so for testing purpose I've added the code in onAuthStateChanged but you can fetch the object or actually store it when page loads.

Categories

Resources