Skip to content
Advertisement

How to get last Firestore ID document

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:

async function pushName(name, surname) {
  const size = getID('Clients');
  const newID = (size + 1).toString();
  const docRef = firebase.firestore().collection('Clients').doc(newID);
  await docRef.set({
    FirstName: name,
    LastName: surname,
  });
  return(
    <View>
      <Text>name: {name}  </Text>
      <Text>surname: {surname}  </Text>
      <Text>size: {size}  </Text>
      <Text>newID: {newID}  </Text>
    </View>
  );
}

async function getID(){
  
  const snapshot = await firebase.firestore().collection('Clients').get().then(function(querySnapshot) {      
    snapshot = querySnapshot.size; 
});
  return snapshot;
}
  

This is the output that i get:

enter image description here

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.

  const size = await getID('Clients');

getID is also too complicated – you should not mix await with then. You can simplify it greatly.

async function getID(){  
  const snapshot = await firebase.firestore().collection('Clients').get()
  return snapshot.size;
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement