Reputation: 1751
I often need the documentId in my local objects after I do a query from Firestore. Since the documentId is no field, I do the following in my queries to achieve this:
const ref = fireDb.collection('users')
const query = await ref.where("name", "==", "foo").get()
let users = []
query.forEach((doc) => {
let user = doc.data()
user.id = doc.id /* <-- Here I add the id to the local object*/
users.push(user)
})
Is there an "easier" way to directly get back a document including its id? Or is this how it should be done?
I do not want to duplicate the documentId into a field, that seems kind of redundant even for a NoSql database.
But since this is something I need to do after pretty much ALL MY QUERIES I wonder if Firestore does not have an option to deliver documents including their ID's?
...I guess that's what they call a first world problem? :)
Upvotes: 0
Views: 57
Reputation: 1751
It seems like there is currently no option to get the documentId directly embedded into an object.
To reduce boilerplate code and keep my code clean I wrote the following helper function that adds the documentId to every object.
And it does that for collections as well as single documents.
Helper Function
const queryFirestore = async function (ref) {
let snapshot = await ref.get()
switch(ref.constructor.name) {
/* If reference refers to a collection */
case "CollectionReference":
case "Query$$1":
let items = []
snapshot.forEach((doc) => {
let item = doc.data()
item.id = doc.id
items.push(item)
})
return items
/* If reference refers to a single document */
case "DocumentReference":
let documentSnapshot = await ref.get()
let item = documentSnapshot.data()
item.id = documentSnapshot.id
return item
}
}
Now in my code...
For a collection:
async getUsers() {
let ref = db.collection("users")
return await queryFirestore(ref)
}
For a single document:
async getUser(userId) {
let ref = db.collection("users").doc(userId)
return await queryFirestore(ref)
}
Upvotes: 1