Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firebase Firestore DocumentReference in Typescript is not returning the document properties

I’m writing a Firebase Cloud Function that will write a Firestore document and then return the documents unique ID to a Flutter app. I’m using Typescript to write my functions.

This is the code that writes the document:

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 that should be of the type DocumentReference and contain the id.
The document is being written to Firestore, but it is not getting the values of the DocumentReference so I can send it back in the response.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The set() method returns a WriteResult object that only has a writeTime property. It’s add() method that returns a DocumentReference so try using that instead as shown below:

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

If you want to use set() then you’ll have to store the document ID before itself like this:

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

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

Either ways, you don’t need {merge: true} as they’ll create a new document.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading