Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore - How to get document id after adding a document to a collection

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) 
like image 876
Brejuro Avatar asked Feb 12 '18 06:02

Brejuro


People also ask

How do I get my ID after adding firestore?

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.

How do I find the number of documents in a collection firestore?

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.

How do I get a specific document from a FireStore collection?

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.

How do I write data to Cloud Firestore?

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.

How to get document by id in Firebase 9 Cloud Firestore?

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)

How to update a count for a specific page in FireStore?

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.


Video Answer


2 Answers

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.

like image 70
Daniel Konovalenko Avatar answered Sep 19 '22 00:09

Daniel Konovalenko


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)     } 
like image 23
Christoffer Avatar answered Sep 20 '22 00:09

Christoffer