i need help with Firestore. I have a database with a collection of Clients that have some documents named by ID (1, 2, 3..)
I want a function that count the number of documents of the collection and create a new document with the value+1 (eg: the last document was 6 and i want a new document 7).
This is what i have done but i don’t know why it doesn’t work:
JavaScript
x
27
27
1
async function pushName(name, surname) {
2
const size = getID('Clients');
3
const newID = (size + 1).toString();
4
const docRef = firebase.firestore().collection('Clients').doc(newID);
5
await docRef.set({
6
FirstName: name,
7
LastName: surname,
8
});
9
return(
10
<View>
11
<Text>name: {name} </Text>
12
<Text>surname: {surname} </Text>
13
<Text>size: {size} </Text>
14
<Text>newID: {newID} </Text>
15
</View>
16
);
17
}
18
19
async function getID(){
20
21
const snapshot = await firebase.firestore().collection('Clients').get().then(function(querySnapshot) {
22
snapshot = querySnapshot.size;
23
});
24
return snapshot;
25
}
26
27
This is the output that i get:
What i do wrong? How can i do it?
Thank you
Advertisement
Answer
Your function getID
doesn’t actually return the count. It returns a promise that eventually resolves with the count. Since it is async, you will need to await
its result to get the value.
JavaScript
1
2
1
const size = await getID('Clients');
2
getID
is also too complicated – you should not mix await
with then
. You can simplify it greatly.
JavaScript
1
5
1
async function getID(){
2
const snapshot = await firebase.firestore().collection('Clients').get()
3
return snapshot.size;
4
}
5