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.
CodePudding user response:
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.