Is there a way that I can get the auto-generated ID for a document created as part of a batch using Firestore?
When using .add()
I can easily get an ID:
db.collection('posts') .add({title: 'Hello World'}) .then(function(docRef) { console.log('The auto-generated ID is', docRef.id) postKey = docRef.id });
Using .batch()
I can add a document with .doc()
and .set()
:
const batch = db.batch(); const postsRef = db.collection('posts').doc(postKey); batch.set(postsRef, {title: 'Hello Again, World'}); const votesRef = db.collection('posts').doc(postKey) .collection('votes').doc(); batch.set(votesRef, {upvote: true}) batch.commit().then(function() { });
Can I get the auto-generated ID of the document that was added to votes
?
Update:
Doug Stevenson is correct - I can access the ID at votesRef.id
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. Create an empty document with an automatically generated identifier, and assign data to it later.
New document with same ID should not be allowed in the same collection. It should be possible to fetch an already existing document from a previous import.
To read a single document, we can use DocumentReference's get() method that returns a Task<DocumentSnapshot>, while reading multiple documents from a collection or Query, we can use Firestore Query's get() method that returns an object of type Task<QuerySnapshot>. Both methods read the data only once.
There is no API to change the ID of an existing document, nor is there an API to move a document. If you want to store the same contents in a different document, you will have to: Read the document from its existing key. Write the document under its new key.
When you call doc() without any arguments, it will immediately return a DocumentReference that has a unique id, without writing anything to the database - the id is generated on the client. So if you want that id, simply use the id property on that DocumentReference. That id will become visible in the database after you've written that document.
I had similar issue, And I thing there were changes at the API of firestore.
I was getting an error for code like :
const postsRef = db.collection('posts').doc(postKey); batch.set(postsRef, {title: 'Hello Again, World'});
The change I found that was necessary is to take the ref
of the doc object:
const postsRef = db.collection('posts').doc(postKey).ref;
I hope this helps you all !
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