The Properties of a Firestore Document are not being correctly retrieved by the DocumentReference in Typescript

I am currently working on a Firebase Cloud Function that is responsible for creating a new Firestore document and then sending back the unique ID of the document to a Flutter application. My functions are written in Typescript.

Below is the code snippet that handles the document creation:

db.collection('devices').doc().set({"deviceId": userId},{merge: true})
    .then((docRef: FirebaseFirestore.DocumentReference<FirebaseFirestore.DocumentData>) => {
        functions.logger.info(`Document path: ${docRef.path}`,{structuredData: true});
        functions.logger.info(`Document written with ID: ${docRef.id}`,{structuredData: true});
        response.status(200).send({"result":"success", "docId": docRef.id});
    })
    .catch((error: Error) => {
        functions.logger.error(error,{structuredData: true});
        response.status(200).send({"result":"error", "message": error.message});
    });

The set method returns a promise with a payload expected to be of type DocumentReference containing the id. The issue I am facing is that even though the document is successfully written to Firestore, I am not able to retrieve the values of the DocumentReference in order to include them in the response.

Answer №1

Utilizing the set() method will give you a WriteResult object containing only the writeTime property. For a more suitable outcome, consider using the add() method that provides a DocumentReference instead:

db.collection("devices").add({ deviceId: userId })
  .then((docRef) => {
    functions.logger.info(`Document written with ID: ${docRef.id}`,{structuredData: true});
  })

If you prefer to use the set() method, you should save the document ID beforehand like this:

const newDocRef = db.collection("devices").doc();

newDocRef.set({ deviceId: userId })
  .then(() => {
    functions.logger.info(`Document written with ID: ${newDocRef.id}`,{structuredData: true});
  })

In both cases, avoid using {merge: true} as it may lead to creating a new document unnecessarily.

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

Assigning dynamic key value pairs in Angular 4 using Typescript

I'm currently attempting to construct an object using keys that are specified in an environment file, meaning the keys would vary depending on the environment. import { environment } from '../environments/environment' export abstract class ...

Ensuring the Presence of a Legitimate Instance in NestJS

I have been working on validating my request with the Product entity DTO. Everything seems to be in order, except for the 'From' and 'To' fields. The validation works correctly for the Customer and Type fields, but when incorrect data i ...

Developing applications using the combination of Vue.js, JSX, and

While I have no issues using TypeScript with single file components (.vue files), I encountered problems when attempting to use it with JSX files. Two errors arise, one in my index.ts file. I'm uncertain if there was a mistake made in my configuration ...

An issue encountered with NSwag in TypeScript-Angular involving enum property names and DateTime data type

Encountering issues with generating enums and DateTime attributes using Nswag and OpenApi. First concern is regarding the Enums generation, aiming for a specific format like: export enum BillboardType { BB = 0, BB18 = 1, Direction = 2, Ban ...

Angular HTTP post is failing on the first attempt but succeeds on the second try

Just started working on my first Angular exercise and encountered an issue where I am receiving an undefined value on the first attempt from an HTTP post request. However, on the second try, I am getting the proper response in Edge and Firefox. Thank you f ...

Managing environment variables in Nuxt with Firebase: Best practices

I have been working on creating a firebase authentication app that is reusable and fully functional. However, despite exploring various online solutions, I have managed to develop a solution that works well. My concern now is about protecting sensitive dat ...

Exploring the differences between Office Fabric UI's I[component]StyleProp and the I[component]Styles interface

The Office Fabric UI documentation provides two interfaces for each component, such as https://developer.microsoft.com/en-us/fabric#/components/nav includes INavStyleProps interface and INavStyles interface A component that implements INavStyleProps ...

What is the best way to update typings.json and typing files?

Here is the structure of my typings.json: { "globalDependencies": { "aws-sdk": "registry:dt/aws-sdk#0.0.0+20160606153210" }, "dependencies": { "lodash": "registry:npm/lodash#4.0.0+20160416211519" } } Currently, I find it tedious to update ...

My goal is to intentionally trigger an eslint error when importing a file from index.ts

Is there a way to enforce importing components from index.ts within the src/components directory using eslint rules or plugins? // index.ts (src/components/Forms) export { Input } from './Input'; export { CheckBox } from './CheckBox'; ...

Is it possible to verify if the @Output is correctly wired up within an Angular component?

When working with Angular and TypeScript, it is possible to access the bound @Input values in the ngOnInit method of a component. However, there isn't a straightforward way to check if a particular @Output event binding has been set up on the componen ...

What strategies should be followed for managing constant types effectively in TypeScript?

enum ENUM_POSITION_TYPE { LEFT = 1, RIGHT = 2 } // type PositionType = 1 | 2 type PositionType = ??? export let a1: PositionType = ENUM_POSITION_TYPE.RIGHT //correct export let a2: PositionType = 1 as const //correct export let a3: PositionType = 3 / ...

Prevent the 'unbound function' ESLint warning when supplying a static method reference to a superclass constructor in TypeScript

Looking to solve a technical problem in my code. I have a class that needs to call its superclass using a function passed as an argument. I specifically want to pass a static function from the same class: export abstract class ChildAdapter extends Adapter{ ...

Unable to update user information immediately after signing up without refreshing the page (Using Next JS and Firebase)

I have been utilizing the Auth Provider for managing my Firebase authentication details. My goal is to access currentUser immediately after signing up, but it seems that it requires a page reload for it to be set. I attempted to call setCurrentUser outsid ...

Can you clarify the meaning of "int" in this code snippet?

What does the ?: and <I extends any[] = any[]> signify in this context, and how is it utilized? export interface QueryConfig<I extends any[] = any[]> { name?: string; text: string; values?: I; types?: CustomTypesConfig; } ...

An error may occur when Typescript is instantiated with a varying subtype of constraint

I am encountering the "could be instantiated with a different subtype of constraint" error when trying to return a result that should match the expected type of a function. Despite removing irrelevant details, I'm struggling to pinpoint what exactly I ...

Challenges arise when attempting to merge declarations in Typescript involving passport, passport-local, and express-session

I'm currently facing challenges trying to integrate passport, passport-local, and express-session with Typescript. After installing all four necessary libraries - @types/passport, @types/express-session @types/passport-local, and @types/express - I in ...

Mastering the art of leveraging generics in conjunction with ngrx actions

Currently, I am in the process of developing an Angular 7 application that utilizes the NGRX store. In our application, we have numerous entities, each with its own dedicated list view. I decided to explore using generics with the NGRX store to avoid writi ...

How to Nest Interfaces in TypeScript

I'm just starting to learn about Angular and I am having trouble getting the interface class to work properly. export interface Header { parentTitles: string; childHeaders: ChildHeader[]; titleIcon: string; url: string; } export interf ...

Error detected in Vuetify project's tsconfig.json file - The configuration file does not contain any input entries

Having an issue with the tsconfig.json file in my Vuetify project. The first { is underlined in red and when hovered over, it displays the error message: No inputs were found in config file Sharing the content of the file below. tsconfig.json { // expe ...

Limitations of Typescript's Index Signature Templates

Currently, I have some Typescript Interfaces with repeated and similar fields. Here's an example: interface Foo { person1Name: string; person1Address: string; person2Name: string; person2Address: string; category: string; department: ...