Reputation: 181
I know its a bit weird question but how can I access the unique (auto) id google firebase generates for my document whenever I create new document. For example this is my code
val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
postCollections.document().set(newPost)
How can I know that what is the id generated for this document of "newPost" because i want to use that id in my code and at the same time i dont want to send custom id because it won't be unique
Upvotes: 0
Views: 159
Reputation: 3499
val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
postCollections.document().set(newPost)
As you've likely discovered, .set()
returns a Promise <void>
.
But what you've ignored is .set()
only operates on a DocumentReference
- which is what you get from postCollections.document()
. A DocumentReference
has properties id
and path
- it is the .document()
that creates a new, unique, documentId.
So:
val postCollections = db.collection("posts")
val newPost = Post(text, user, currentTime)
val newRef = postCollections.document()
newRef.set(newPost)
And now you have the document id (and path) available as properties of newRef.
https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference
Upvotes: 2