I’m looking to add the Firestore ID to the DocumentData, so that I can easily utilize the ID when referring to rows in a table, without having to use document.data().property everytime I call a property of a document. Instead, I want to be able to call document.id…. document.property… and so on.
Is there an easy way to do this? Possibly with a Cloud Function that adds the auto-generated ID to the document data?
Thanks!
Example:
export const getSpaces = async () => {
const spaceDocs = await getDocs(spacesCollection)
spaceDocs.docs.forEach((spaceDoc) => {
const spaceID = spaceDoc.id
const spaceData = spaceDoc.data()
console.log(spaceID)
spaces.value.push(spaceData)
})
}
Now, the spaces array has objects containing the data of the documents. But, I loose the ability to reference the ID of a document.
Alternatively, I can add the entire document to the array, but following that, I’ll have to access the properties by always including the data() in between. I.e. space.data().name
I’m certain, theres a better way
3
Answers
Working on another problem, I came across the solution. Quite simple actually:
When declaring the new Object, you can add
...doc.data()
to add all the properties of the DocumentData to the newly created Object, after initialising it with an id. This works for me anyways. Case closed.A DocumentSnapshot has
id
property that you are looking for. If you add something within the document, then you’ll need to access the data first withdoc.data().field_name
.You don’t need Cloud Functions to add the document ID to the data of that document. If you look at the third code snippet in the documentation on adding a document, you can see how to get the ID before writing the document.
As others have commented, you don’t need to store the ID in the document. You can also add it to your data when you read the documents, with:
With this change your
spaces
contains both the document ID and the data of each document.