Is there a way to retrieve the automatically generated ID for a document that was created with batch().set in Firestore?

Is there a method to retrieve the automatically generated ID for a document that is created as part of a batch operation in Firestore?

Typically, when using .add(), obtaining an ID is straightforward:

db.collection('posts')
  .add({title: 'Hello World'})
  .then(function(docRef) {
    console.log('The auto-generated ID is', docRef.id)
    postKey = docRef.id
});

However, when utilizing .batch() to add documents 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() {
});

The question now arises - can we obtain the auto-generated ID for the document added to votes collection?

Update:

According to Doug Stevenson's clarification, the ID can indeed be accessed via votesRef.id

Answer №1

When invoking the doc() method without any parameters, it will promptly provide you with a DocumentReference that contains a unique identifier, without actually saving anything to the database - the identifier is created on the client side. If you require this identifier, simply access the id property of the DocumentReference object. This identifier will only be visible in the database after the document has been written.

Answer №2

It seems like I encountered a similar issue, and it appears that there may have been some modifications to the API of firestore.

An error kept popping up for code snippet such as:

const postsRef = db.collection('posts').doc(postKey);
batch.set(postsRef, {title: 'Hello Again, World'});

The necessary change that solved the problem was to obtain the ref of the doc object:

const postsRef = db.collection('posts').doc(postKey).ref;

I hope this information is useful for everyone!

Answer №3

If you want to automatically generate a unique ID before creating a document, you can use the createID() function from angularFireAuth in the following way:

`

constructor(
    private angularFireStore: AngularFirestore,
   ) {}

 const batch = this.angularFireStore.firestore.batch();

 const autogenUid = this.angularFireStore.createId();
 const collectionReference = this.angularFireStore.collection
                            ('collection_name').doc(autogenUid).ref;

 const docData = {first_field:'value', second_field:'value2'};
 batch.set(collectionReference, docData);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting axios response containing an array of arrays into a TypeScript interface

When working with an API, I encountered a response in the following format: [ [ 1636765200000, 254.46, 248.07, 254.78, 248.05, 2074.9316693 ], [ 1636761600000, 251.14, 254.29, 255.73, 251.14, 5965.53873045 ], [ 1636758000000, 251.25, 251.15, 252.97, ...

Preventing CSRF Attacks in an HTML Application with Laravel Route Protection

Currently, I am facing a challenge while developing an app with the PhoneGap API as it interferes with Laravel's 'View' property. Additionally, another issue arises as the index file must be in .html format, leaving me unsure of how to enha ...

Make TypeScript parameter optional if it is not supplied

I am working with an interface that defines scenes and their parameters: export interface IScene<R extends string> { path: R; params?: SceneParams; } The SceneParams interface looks like this: export interface SceneParams { [key: string]: s ...

Defining the limits for a JavaScript canvas game

I am currently working on a game project for school using HTML5 canvas and JavaScript. As I am still a beginner in JavaScript, I am facing a specific issue that I could use some assistance with. Despite trying various solutions, I have been unable to figur ...

"When I use breakpoints and run my application in debugging mode, it performs flawlessly. However, without these tools, it

I have developed an application using the Ionic Framework with Firebase as the backend. When I run the application with breakpoints using the debugger, everything works fine. However, if I run it without the debugger, I notice that values are not being upd ...

Exploring the dynamic loading of components within routes

Just starting out with Vue and experimenting with vue-router, I'm trying my hand at dynamically loading components without relying on additional libraries like webpack. So far, I've set up an index page and a router. Upon initial page load, I not ...

Is there a way to verify if a folder exists at the root of the project?

I'm currently working on a NPM script where I have a folder called "scripts" that contains all of my scripts. My goal is to check if there is a folder named "docs" at the root of the project, and if it exists, delete it. If not, then perform another t ...

Guide on looping through deeply nested children within an object to accumulate a list of names

Within an object, there are numerous parent and child elements var obj={ name: 'one', child:{ name: 'two', child:{ name: 'three', child.. } } } foo(obj) Create a ...

Find all guests within a specified date range using Firebase

Struggling with developing a hotel management app using vue, vuex, and firestore. Currently stuck on querying guests within a specific date range, such as those who checked in yesterday but are still checked in today. The standard .where("arrival", "<=" ...

Ways to reach the Document Object Model in a functional component

While working on a speedometer project in ReactJS with some vanilla syntax, I encountered an issue where the canvas element was returning null. Oddly enough, when running const canvas = document.getElementById('dial__container'); in the console, ...

What is the best way to organize React components/modules in order to effectively separate the UI?

Currently, I have developed three key components for a dashboard UI project in React. These components include a sidebar, top navigation bar, and a content container. As someone who is new to React after working with Angular, I am now seeking advice on how ...

Creating an error message display function using HTML and JavaScript when incorrect input is detected

I am having trouble creating an HTML5 and JS program that will show an error message if the user input is empty. Despite my efforts, I can't seem to get the "Error Message" to display. As a beginner, the video tutorial I'm following doesn't ...

The button fails to trigger the AJAX request

I've developed a form that includes a QR code generator. The QR code is generated as an SVG, and below the code is a download button that should trigger an AJAX call to my PHP script when clicked. However, the download button does not seem to initiate ...

Integrating information from various sources to create a cohesive online platform

I am looking to incorporate data from various sources into a single web page: Social networks (Facebook, Twitter, LinkedIn, etc.) RSS feeds Article meta tags (particularly OpenGraph and Twitter cards) This data may change dynamically based on user inter ...

After reloading the data tables, analyze the information and dynamically highlight any rows in red that remain unchanged

I have a table that is refreshed every 5 minutes using ajax.reload(). One of the rows in this table is labeled as CIP. My goal is to highlight the CIP row on each refresh where the value remains unchanged from the previous value (value received in the la ...

What is the best method for interacting with multiple links in Puppeteer?

As a beginner with puppeteer, I am diving into the world of web scraping by attempting to create a simple scraping task. My Plan of Action The plan is straightforward: Visit a page, Extract all <li> links under a <ul> tag, Click on each < ...

The onclick function in HTML will only be executed during the initial click event

I've been working on creating a To-Do list and have managed to add all the necessary functionalities. However, I encountered an issue where the edit function only works the first time it is clicked. I tried searching for solutions online as I am rela ...

What is the method for displaying a canvas scene within a designated div element?

I need help displaying a scene inside an existing div on my webpage. Whenever I try to do this, the canvas is always added at the top of the page. I attempted to use getElementById but unfortunately, it didn't work as expected. What could I be overlo ...

Having trouble making Three.js with instancing work properly unless FrustumCulling is set to false

I've encountered an issue with three.js and instancing, similar to what others have experienced. The objects are randomly clipped and disappear from the camera view. Examples can be found here. Mesh suddenly disappears in three.js. Clipping? Three.j ...

Tips for recalling the display and concealment of a div element using cookies

My HTML code looks like this: <div id='mainleft-content'>content is visible</div> <div id="expand-hidden">Button Expand +</div> To show/hide the divs, I am using JQuery as shown below: $(document).ready(function () { ...