2

I'm new to making a simple website that use cloud firestore as a database. When the user add new data, I let firestore generating the document ID automatically (as the image). Now I want to get that document ID but I have no idea about that. Here is my code:

  db.collection("todos").add({
    content: input.value,
    name: name.value,
    time_update: time
  })
  .then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
    return documentId = docRef.id // i try to do this but it does not return the documentID outside this promise
  })
  .catch(function(error) {
    console.error("Error adding document: ", error);
  });

image for more understandable

when I use console.log(documentId) outside that promise, it returned "undefined". Please help, thank you!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    I think that this is not a duplicate as the real problem here is understanding how promises work, not how to get the ID. Short explanation for OP: JS likes to be asynchronous, so promises and callbacks are everywhere. The problem in your code is that the ".then()" can be executed long time after other instructions are processed. So, you should place your console.log in the callback of your .then(). You would have given a more detailed explanation, but the question was closed, so you could have a read about promises here: https://www.freecodecamp.org/news/javascript-promises-explained/ – Mihail Feraru Jul 25 '20 at 20:41
  • 1
    This should be your actual question: https://stackoverflow.com/questions/47559836/how-can-i-access-a-variable-outside-a-promise-then-method – Mihail Feraru Jul 25 '20 at 20:42

1 Answers1

1

You don't need to wait for the callback. You can get a random ID immediately:

const docRef = db.collection("todos").doc()
const id = docRef.id

Then add the data using set():

docRef.set(...)

The random IDs are generated on the client, not on the server.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441