I'm having an issue getting the collection info. Using this code, I could only get the doc with a specific uid.
const snapShot = doc(db, 'Files', 'someUID');
const getSnapShot = await getDoc(snapShot);
console.log(getSnapShot.data());
I used this code to get all of the collection items but threw an error.
const snapShot = collection(db, 'Files');
const getSnapShot = await getDoc(snapShot);
console.log(getSnapShot.forEach(doc => console.log(doc.data()));
Uncaught (in promise) FirebaseError: Expected type 'wc2', but it was: a custom gc2 object
Q: How do I make it work?
To get all documents from a collection or documents that match a query you should use getDocs() instead of getDoc() that is used to fetch a single document as the function name suggests.
const snapShot = collection(db, 'Files');
const getSnapShot = await getDocs(snapShot);
console.log(getSnapShot.forEach(doc => console.log(doc.data()));
Related
Im getting an error with firebase because im trying to update two values when I press handleSelect. Only issue is that the first updateDoc works fine as I'm trying to add an array into the "user" specific userChats database, but when I try to do the opposite and add the user array to the "chat" database, it fails.
const handleSelect = async(chat) =>{
const docRef = doc(db, 'users', user?.uid)
const docSnap = await getDoc(docRef)
const addRef = doc(db, 'userChats', user?.uid)
await updateDoc(addRef, {
userChats: arrayUnion(chat)
})
const addRecieverRef = doc(db, 'userChats', chat?.uid)
await updateDoc(addRecieverRef, {
userChats: arrayUnion(user)
})
console.log(chat.uid)
const concatUID = user.uid > chat.uid ? user.uid + chat.uid : chat.uid + user.uid;
if(!docSnap.exists() && user.uid!=chat.uid){
await setDoc(doc(db, 'messages', concatUID), {
messages: [],
})
}
else{
dispatch({type: 'CHANGE_USER', payload: chat})
console.log(chat)
}
}
Error
Chats.js:53 Uncaught (in promise) FirebaseError:
Function arrayUnion() called with invalid data.
Unsupported field value: a custom UserImpl object (found in document userChats/lJ4u4PqWynXAPthz3FVgYaQQ0Do1)
I already checked and all the reference values are correct, and both "user" and "chat" are plain objects
Firestore can only store values of the types indicated in its documentation on data types. The UserImpl object that you are trying to store is not of a supported type, which is what the error message indicates.
If the user object comes from Firebase Authentication, you can call toJSON() on it to get a JSON serialization of its data.
I am currently encountering this problem in my react native app using Firebase:
Collection references must have an odd number of segments
I've seen similar cases in stackoverflow but wasn't able to solve my problem. Here is my code :
const getData = async () => {
console.log(user.uid + " 🚧🚧🚧")
const col = collection(db, "users", user.uid)
const taskSnapshot = await getDoc(col)
console.log(taskSnapshot)
}
getData()
I am trying to open my document with the document reference (user.uid) but I am getting this error : Collection references must have an odd number of segments
Hope you can help me solve this problem.
The getDoc() takes a DocumentReference as parameter and not a CollectionReference so you must use doc() instead of collection().
import { doc, getDoc } from "firebase/firestore"
const docRef = doc(db, "users", user.uid)
const taskSnapshot = await getDoc(col)
console.log(taskSnapshot.data() || "Doc does not exists")
Also checkout Firestore: What's the pattern for adding new data in Web v9?
replace this
collection(db, "users", user.uid)
with this
collection(db).document("users").collection(user.uid)
I'm struggling to complete the following code:
const myCollection = collection(db, 'myCollection');
const mycollectionQuery = query(myCollection, where("field1", "==", "xyz"));
myCollectionSnapshot.forEach((doc) => {
deleteDoc(?);
});
Advice on what to supply inside the deleteDoc call would be much appreciated. I was pretty confident it would be doc.id, but this returns a "Cannot use 'in' operator to search for '_delegate' in undefined" error message
In V9, the deleteDoc() method takes a DocumentReference, as documented here.
As you can see from the documentation of your forEach(), the doc variable will be a QueryDocumentSnapshot, that is a specialization of DocumentSnapshot. It means that, if you want to retrieve the DocumentReference for your doc, you just need to reference to it via doc.ref.
In other words, to delete the document you'll need to do this:
myCollectionSnapshot.forEach((doc) => {
deleteDoc(doc.ref);
});
This is how you delete a document from cloud firestore:
deleteDoc(doc(db, "reference"))
So, the complete code is:
const myCollection = collection(db, 'myCollection');
const mycollectionQuery = query(myCollection, where("field1", "==", "xyz"));
myCollectionSnapshot.forEach((doc) => {
deleteDoc(doc(db, doc.ref));
});
This logs the snapshot:
const db = firebase.firestore();
const collection = db.collection(`companies/${company}/meetings`);
let query = collection.where('start', '>=', new Date());
const snapshot = await query.limit(10).get();
console.log(snapshot);
This doesn't:
const db = firebase.firestore();
const collection = db.collection(`companies/${company}/meetings`);
let query = collection.where('start', '>=', new Date());
if (branch) {
query = query.where('branch', '==', branch);
}
const snapshot = await query.limit(10).get();
console.log(snapshot);
Does anyone know why?
Since you are combining the '>=' and '==' operators, Firestore needs to build an index for this query.
If you catch the error with a try/catch block, you will see the corresponding error, and, even better, the error message includes a direct link to create the missing index in the Firebase console.
See the doc here for more details on indexing in Firestore.
I have a collection called 'categories' containing a single document with ID: 5gF5FqRPvdroRF8isOwd.
I have another collection called 'tickets'. Each ticket has a reference field which assigns the ticket to a particular category.
The field in the tickets collection is called 'category' and has a field type of reference.
In the code below, categoryDocId is the document ID of the category I want to query by.
const categoryDocID = `5gF5FqRPvdroRF8isOwd`;
const files = await firebase
.firestore()
.collection('tickets')
.where('category', '==', categoryDocID)
.get();
Why does files.length return 0?
For testing, I changed the category field type to string, and set it to the category ID instead of a direct reference. This correctly returned tickets assigned to the category, which leads me to believe it's something about how I'm querying a reference field.
As you will read here in the doc, the Reference Data Type is used to store DocumentReferences.
If you want to use it in a query, you cannot use a simple string, neither the UID of the document (i.e. '5gF5FqRPvdroRF8isOwd'), nor the string value that is stored in the field (i.e. '/categories/5gF5FqRPvdroRF8isOwd').
You have to build a DocumentReference and use it in your query, as follows:
JS SDK V9
import { doc, query, collection, where, getDocs } from "firebase/firestore";
const categoryDocRef = doc(db, "categories", "5gF5FqRPvdroRF8isOwd");
const q = query(
collection(db, "tickets"),
where("category", "==", categoryDocRef)
);
const files = await getDocs(q); // !! files is a QuerySnapshot
JS SDK V8
const categoryDocRef = firebase.firestore()
.collection('categories')
.doc('5gF5FqRPvdroRF8isOwd');
const files = await firebase // !! files is a QuerySnapshot
.firestore()
.collection('tickets')
.where('category', '==', categoryDocRef)
.get();
With Firebase Version 9 (Dec, 2021 Update):
You must make a document reference with "categories/5gF5FqRPvdroRF8isOwdand" then use it in your query:
import { doc, query, collection, where, getDocs } from "firebase/firestore";
const categoryDocRef = doc(db, "5gF5FqRPvdroRF8isOwd");
const q = query(
collection(db, "tickets"),
where("category", "==", categoryDocRef)
);
const ticketDocsSnap = await getDocs(q);
Here is how I use reference type to query a collection (node.js + typescript):
let myCollectionADocument = await admin.firestore().collection("collection_a").doc("documentId").get();
let myCollectionB = await admin.firestore().collection("collection_b").where("collection_a_id", "==", myCollectionADocument.ref).get();