Is there a way to acquire the document id that was generated after adding a document to a collection?
If I add a document to a collection that represents a "post" in a social media app, I want to get that document id and use it as a field in another document in a different collection.
If I can't get the document Id that was generated after adding a document, should I just compute a random string and supply the id when creating the document instead? That way I can use that same string as the field in my other document?
Quick structure example:
POST (collection) Document Id - randomly generated by firebase or by me USER (collection) Document Id - randomly generated by firebase userPost: String (this will be the document id in the post collection that I'm trying to get)
When you call the . add method on a collection, a DocumentReference object is returned. DocumentReference has the id field, so you can get the id after the document was created. // Add a new document with a generated id.
If you need a count, just use the collection path and prefix it with counters . As this approach uses a single database and document, it is limited to the Firestore constraint of 1 Update per Second for each counter.
Import Firestore Database and de-structure the three methods that we need: doc () → It takes references of database, collection name and ID of a document as arguments getDoc () → getDoc () query gets data of a specific document from collection based on references mentioned in the doc () method.
There are several ways to write data to Cloud Firestore: Set the data of a document within a collection, explicitly specifying a document identifier. Add a new document to a collection. In this case, Cloud Firestore automatically generates the document identifier.
Learn how to get document by ID using the getDoc () method in Firebase version 9 Cloud Firestore Database. The sample Firestore Database has a cities collection that has four documents in it like in the screenshot below. Let’s get the first document of the cities collection by id. In this case: Edmonton document using its ID ( 2l3bcSGs2vZBIc3RODwp)
Another option is to use a Firestore Cloud Function to update a count for each newly-created document. This is especially useful if you want to query a specific page in paginated query. Goal: Maintain a sequential count on each document in the collection. The first document is number: 1, second number: 2, and so on.
Yes it is possible. When you call the .add
method on a collection, a DocumentReference object is returned. DocumentReference has the id
field, so you can get the id after the document was created.
// Add a new document with a generated id. db.collection("cities").add({ name: "Tokyo", country: "Japan" }) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); }) .catch(function(error) { console.error("Error adding document: ", error); });
This example is in JavaScript. Visit the documentation for other languages.
If using promises, I'd recommend using fat arrow function as it opens up the possibility for using this.foo
even in the .then
function
db.collection("cities").add({ name: "Tokyo", country: "Japan" }) .then(docRef => { console.log("Document written with ID: ", docRef.id); console.log("You can now also access this. as expected: ", this.foo) }) .catch(error => console.error("Error adding document: ", error))
Using function(docRef)
means you cannot access this.foo
, and error will be thrown
.then(function(docRef) { console.log("Document written with ID: ", docRef.id); console.log("You can now NOT access this. as expected: ", this.foo) })
While fat arrow functions will allow you to access this.foo
as expected
.then(docRef => { console.log("Document written with ID: ", docRef.id); console.log("You can now also access this. as expected: ", this.foo) })
Edit/addition 2020:
A more popular way these days may be to use async/await instead. Notice that you have to add async
in front of the function declaration:
async function addCity(newCity) { const newCityAdded = await db.collection("cities").add(newCity) console.log("the new city:", newCityAdded) console.log("it's id:", newCityAdded.id) }
And if you only want the id it can be grabbed using descructuring. Destructuring allows you to grab any key/value-pair in the response:
async function addCity(newCity) { const { id } = await db.collection("cities").add(newCity) console.log("the new city's id:", id) }
It's also possible to use destructuring to grab the value and rename to whatever you want:
async function addCity(newCity) { const { id: newCityId } = await db.collection("cities").add(newCity) console.log("the new city's id:", newCityId) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With