How can I set a document ID as a variable in Firebase Firestore?

I recently set up a firestore collection and successfully added data (documents) to it. Firestore conveniently generates unique document ids for each entry.

Inserting Data

this.afs.collection('questions').add({ 'question': message, 'asker': this.currentStudent, 'upvotes': this.upvote, 'lesson': this.currentLesson });

Now, I am eager to retrieve the document id of the newly inserted data and store it in a variable. Something along these lines:

this.documentId = newlyInsertedDocumentId

I recall hearing about using the document.Set() method for achieving this task. Can someone guide me on how to implement this?

Answer №1

The method add() will give you a promise in return. Once this promise is resolved, it will provide you with the DocumentReference for the newly created document.

To retrieve this DocumentReference, you can use the following code:

this.afs.collection('questions')
    .add({ 'question': message, 'asker': this.currentStudent, 'upvotes': this.upvote, 'lesson': this.currentLesson })
    .then(function(documentRef) {
        documentId = documentRef.id;
    });

For additional information, you may refer to my response on this post: Firebase: Get document snapshot after creating

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

Having issues with matSort functionality on mat-table in Angular

The content of my .html file is shown below: <mat-table [dataSource]="dataSource" padding matSort> <ng-container matColumnDef="uid"> <mat-header-cell *matHeaderCellDef mat-sort-header> Building UID </mat-header-cell&g ...

The Formik and React error is indicating that the '{ refetch: any; }' type is absent

When attempting to pass a prop down to my EmailSignupScreen, I encountered an error message. This issue arose while experimenting with Formik and Typescript. "message": "Type '{ refetch: any; }' is missing the following properties from type &apo ...

Top method for verifying input during keyup or blur events

When it comes to validating user inputs, I often find myself wondering about the best approach to take. In this case, I have created a regex for numbers with decimal points. .ts part checkIsNumber(event) { console.log('event', event.target. ...

Converting a string to a Date in Angular2 using Typescript

I need to initialize a new Date object using a specific date. I have considered converting it from a particular string, like so: let dateString = '1968-11-16T00:00:00' How can I achieve this in typescript? Update: I am specifically looking fo ...

Ways to resolve the issue: ""@angular/fire"' does not contain the exported member 'AngularFireModule'.ts(2305) in an ionic, firebase, and

I am facing an issue while attempting to establish a connection between my app and a firebase database. The problem arises as I receive 4 error messages in the app.module.ts file: '"@angular/fire"' has no exported member 'AngularFi ...

Adjust the observable value when making an API call

I have an observable that emits values from an API. In the component where it's subscribed, I want to update the observable value on a certain event. I'm struggling to figure out how to do this. Here is the code in the service class: cacheSett ...

Empty nested Map in POST request

I am currently working on a springboot application with a React/Typescript frontend. I have defined two interfaces and created an object based on these interfaces. export interface Order { customer_id: number; date: Date; total: number; sp ...

Exploring the world of Angular, .NET Core, and managing server

Is it still common practice to utilize server sessions for storing information? I have a website built in Angular with a C# backend, and currently, whenever the frontend requires data, it fetches it from the backend via its API. This results in the backend ...

The eventsource property binding in Ionic 2 calendar does not correctly refresh the view

As a newcomer to the world of Ionic, Angular, and TypeScript, I am currently working on developing a calendar that allows users to set appointments (events) and make edits or deletions to them. To achieve this functionality, I have implemented a modal for ...

Angular project models

I'm exploring the Core/Shared/Feature design pattern for building large, scalable applications in Angular, and I find myself unsure about where models fit in. Is there a consensus on which module they belong in? I came across a post suggesting that ...

Incorporating TypeScript into a project that already contains .js files

I currently have a NodeJS project with .js files written in ES6. I am interested in integrating typescript into this existing project. What steps should I follow? Can I simply introduce .ts files within the same directory structure? One issue I have encou ...

Exploring the Differences Between ionViewWillEnter and ionViewDidEnter

When considering whether to reinitiate a cached task, the choice between ionDidLoad is clear. However, when we need to perform a task every time a view is entered, deciding between ionViewWillEnter and ionViewDidEnter can be challenging. No specific guid ...

How can Angular utilize dynamic InjectionTokens according to routes?

I am curious about the best way to initiate a service that relies on another service and a complex object used for creating a dependency within the service. Currently, I am utilizing an InjectionToken to inject the complex object into the service, but I re ...

Creating unique components with Angular2 and Ionic

Here is the HTML code for my custom component: <div> {{text}} {{percentLeft}} {{innerColor}} </div> And here is the TypeScript file for my component: import { Component, Input } from '@angular/core'; @Component({ selector: ...

Is it possible to have unique styles for individual tabs in a mat-tab-group using Angular Material?

Is it possible to have different text colors for each tab in a mat-tab-group and change the color of the blue outline at the bottom? If so, can you provide guidance on how to achieve this? Here is the default appearance of the tabs in my app: https://i.st ...

Unable to include option object in the SHA3 function using typescript

The SHA3 function allows for customizing the output length, as demonstrated in the code snippet below: var hash = CryptoJS.SHA3("Message", { outputLength: 512 }); var hash = CryptoJS.SHA3("Message", { outputLength: 384 }); var hash = CryptoJS.SHA3("Messag ...

Tips for handling various HTTP requests until a response is received

For my application, I have a need to make multiple http calls before proceeding to create certain objects. Only after all the http requests have received responses from the servers can I process the results and construct my page. To handle this scenario, ...

Simultaneous asynchronous access to a single object

I have been working with JS/TS for quite some time now, but the concept of race conditions still perplexes me. I am currently attempting to execute the following logic: class Deployer { protected txDataList: Array<TXData>; constructor() { this ...

Ways to differentiate between the sources of two cold Observables (not just the possible data streams they may produce)

Situation: Within my Angular application, I am using publishReplay to store and replay specific Http requests. However, I encountered an issue where I need the cached observable source to update itself and create a new cached observable with publishReplay ...

Adding dependency service to the parent class in Angular

I am working with classes parent and child. The child class is an extension of the parent class. I want to inject the injectable class service into the parent class since all instances of the child class will be using it as well. Can someone guide me on ...