I have a react native function to to get all collection documents as follows
export const fetchAuctionItems = () => {
return firestore().collection('items').get();
};
When I'm accessing above function response not getting any documents instead that I'm getting following
Can anyone one help me to solve my problem, Thank you
collection.get() returns a a QuerySnapshot and this is the data you are seeing. You need to request the data from the QuerySnapshot, like so for example.
export const fetchAuctionItems = () => {
return firestore().collection('items')
.get()
.then(querySnapshot => querySnapshot
.docs
.map(d => ({
id: d.id,
...d.data(),
});
};
Read more about QuerySnapshot here
Related
My problem is that I use wrong query to get the date.
const SaveDateBase = async ( e) => {
e.preventDefault()
await setDoc(doc(db, "Users", "Pompy", "Pompy", user.uid), {
displayName: user.displayName,
uid: user?.uid,
modulyPV}).then(()=>{
console.log("moduly", modulyPV)
})
};
useEffect(() => {
const getUsers = async (users) => {
const URC = query(collection(db, "Users").document("Pompy").collection("Pompy"), where("uid", "==", user?.uid));
const data = await getDocs(URC)
setModulyPV(data.docs.map((doc) => ({...doc.data(), id: doc.id})))
}
getUsers();
},[])
The date are saved in date base, and I can successfully update/delete them, but I do something wrong to fetch (read?) them.
I guess is problem with the code.
You can get the data in diff ways, first "Pompy" seems to be your document where you are storing a nested collection then you document "Pompy" So for retrieve that specific document should be something like:
let snapshot = await db
.collection('Users')
.doc('Pompy')
.collection('Pompy')
.get()
snapshot.forEach(doc =>{
console.log('data:', doc.data())
})
Then to query into the nested collection would be something like querying the nested collections.
https://cloud.google.com/firestore/docs/samples/firestore-data-get-sub-collections?hl=es-419#firestore_data_get_sub_collections-nodejs
You can also use collection groups.
https://firebase.google.com/docs/firestore/query-data/queries#collection-group-query
const pompys = query(collectionGroup(db, 'Pompy'), where("uid", "==", user?.uid));
Im trying to implement code in Firestore which will get the values of a specific object inside a doc in firestore, unfortunently i couldnt find the way to do it.
This is my query code:
useEffect(() => {
firebase
.firestore()
.collection("users")
.doc(uid)
.collection("confirmed-appointments")
.get()
.then((snapshot) => {
let service = [];
snapshot.forEach((doc) => {
service.push(doc.data());
});
console.log("Services: ", service[0].servicesSelected); //Checking if i can get the serviceSelected Obj
});
}, []);
This is a image of the firestore:
What i want is to get the data of the Red circle object, move it to a local object in the code and then present its data inside the app.
any suggestions?
As far as I can tell from the above images, document 10 contains an array, which means that you will need to index into that array in order to get its elements. You can leverage the following code to fetch the servicesSelected object fields:
import firestore from '#react-native-firebase/firestore';
firestore()
.collection('users')
.doc(uid)
.collection("confirmed-appointments")
.get()
.then(querySnapshot => {
//let service = [];
console.log('Total confirmed appointments: ', querySnapshot.size);
querySnapshot.forEach(documentSnapshot => {
console.log("Services Selected: ", documentSnapshot.data().YOUR_ARRAY[1].servicesSelected);
//service.push(documentSnapshot.data());
//console.log('Appointment ID: ', documentSnapshot.id, documentSnapshot.data());
});
});
Note that I assume that servicesSelected lives at index 1 of YOUR_ARRAY (replace YOUR_ARRAY with its actual name).
You can refer to the officially recommended documentation for more details about React Native for Firebase.
I would just like to access my Firestore Database from within my Firebase Functions. I have tried to follow all the documentation and other stack overflow questions but still it is not working. Here is my code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.test = functions.https.onRequest((request, response) => {
admin
.firestore()
.collection('users')
.get()
.then(querySnapshot => {
const arrUsers = querySnapshot.map(element => element.data());
return response.send(arrUsers);
}).catch((error) => {
// It is coming in here, and this below just returns '{}'
response.send(error);
});
});
What am I doing wrong?
The get() method of a CollectionReference returns a QuerySnapshot which "contains zero or more DocumentSnapshot objects representing the results of a query. The documents can be accessed as an array via the docs property or enumerated using the forEach() method".
Therefore you should do as follows, calling map() on querySnapshot.docs:
exports.test = functions.https.onRequest((request, response) => {
admin
.firestore()
.collection('users')
.get()
.then(querySnapshot => {
const arrUsers = querySnapshot.docs.map(element => element.data());
//return response.send(arrUsers); //You don't need to use return for an HTTPS Cloud Function
response.send(arrUsers); //Just use response.send()
}).catch(error => {
//response.send(error);
response.status(500).send(error) //use status(500) here
});
});
Note the changes to the code for returning the response and handling the error. I would suggest that you watch this official Firebase video on HTTPS Cloud Functions: https://www.youtube.com/watch?v=7IkUgCLr5oA, it's a must!
I'm trying to delete many docs with specific categoryId value from my collection, but I'm doing this in a wrong way I think.
async deleteCol(id: string) {
const cars: firebase.firestore.QuerySnapshot
= await this.db.collection('cars', ref => ref.where('categoryId', '==', id)).ref.get();
const batch = this.db.firestore.batch();
cars.forEach(car => {
batch.delete(car);
});
batch.commit();
}
There are two problems:
typescript shows an error for car in batch.delete(car);
Argument of type 'QueryDocumentSnapshot' is not assignable to parameter of type 'DocumentReference'. Property 'firestore' is missing in type 'QueryDocumentSnapshot'.
If there are for example two cars and each has different categoryId, then forEach is triggered twice (for each document, not for document with specific categoryId), but should only one time or maybe there is a better and easier way to delete all docs by specific condition?
UPDATE:
Ok, so this version is working :)
public async deleteCol(id: string): Promise<void> {
const carsList: Observable<firestore.QuerySnapshot> = await this.db.collection('cars', ref => ref.where('categoryId', '==', id)).get();
const batch = this.db.firestore.batch();
carsList.pipe(
mergeMap(cars => cars.docs),
map((car: QueryDocumentSnapshot) => batch.delete(car.ref))
).toPromise().then(() => batch.commit());
}
I got a querysnapshot in a function.
And want to bring the whole querysnapshot to another function (functionTwo).
In functionTwo, I want to get a specific document in the querysnapshot WITHOUT forEach. The specific doc can be changed by different cases.
ref_serial_setting.get()
.then(querysnapshot => {
return functionTwo(querysnapshot)
})
.catch(err => {
console.log('Error getting documents', err)
})
let functionTwo = (querysnapshot) => {
// getting value
const dataKey_1 = "dataKey_1"
// Tried 1
const value = querysnapshot.doc(dataKey_1).data()
// Tried 2
const value = querysnapshot.document(dataKey_1).data()
// Tried 3 (Put 'data_name': dataKey_1 in that doc)
const value = querysnapshot.where('data_name', '==', dataKey_1).data()
}
The result are all these trying are not a function.
How can I get specific document data from querysnapshot??
or
Is there any easy method to change the querysnapshot to JSON?
You can get an array of the document snapshots by using the docs property of a QuerySnapshot. After that you'll have to loop through getting the data of the doc snapshots looking for your doc.
const docSnapshots = querysnapshot.docs;
for (var i in docSnapshots) {
const doc = docSnapshots[i].data();
// Check for your document data here and break when you find it
}
Or if you don't actually need the full QuerySnapshot, you can apply the filter using the where function before calling get on the query object:
const dataKey_1 = "dataKey_1";
const initialQuery = ref_serial_setting;
const filteredQuery = initialQuery.where('data_name', '==', dataKey_1);
filteredQuery.get()
.then(querySnapshot => {
// If your data is unique in that document collection, you should
// get a query snapshot containing only 1 document snapshot here
})
.catch(error => {
// Catch errors
});
Theres an easy way to do this, each QuerySnapshot has a property docs which returns an array of QueryDocumentSnapshots. See QuerySnapshot documentation.
let citiesRef = db.collection('cities');
let query = citiesRef.where('capital', '==', true).get().then(snapshot => {
snapshot.docs[0]; // => returns first document
});
let citiesRef = db.collection('cities');
let query = citiesRef.where('capital', '==', true).get()
.then(snapshot => {
if (snapshot.empty) {
console.log('No matching documents.');
return;
}
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
.catch(err => {
console.log('Error getting documents', err);
});
from https://firebase.google.com/docs/firestore/query-data/get-data
you can use this code :
const querySnapshot = await getDocs(collection(db, "collectionNaame"));
const docSnapshots = querySnapshot.docs;
for (var i in docSnapshots) {
console.log(i)
const doc = docSnapshots[i].data();
console.log(doc)
Just do
db.doc(<<ref>>).get()
this returns a promise
[here ]: https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document is the link to the docs