Reputation: 55
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);
});
when I use console.log(documentId) outside that promise, it returned "undefined". Please help, thank you!
Upvotes: 2
Views: 255
Reputation: 317392
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.
Upvotes: 1