从 Firestore 进行查询后,我经常需要本地对象中的 documentId。由于 documentId 不是字段,因此我在查询中执行以下操作来实现此目的:
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)
})
是否有一种“更简单”的方法可以直接取回文档(包括其 ID)?还是应该这样做?
我不想将 documentId 复制到字段中,即使对于 NoSql 数据库来说,这似乎也有点多余。
但是,由于这是我在询问了几乎所有问题之后需要做的事情,我想知道 Firestore 是否没有选项来提供包括其 ID 在内的文档?
...我想这就是他们所谓的第一世界问题? :)
最佳答案
目前似乎没有选项可以将 documentId 直接嵌入到对象中。
为了减少样板代码并保持代码整洁,我编写了以下辅助函数,将 documentId 添加到每个对象。
它对集合和单个文档都执行此操作。
辅助函数
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
}
}
现在在我的代码中...
对于集合:
async getUsers() {
let ref = db.collection("users")
return await queryFirestore(ref)
}
对于单个文档:
async getUser(userId) {
let ref = db.collection("users").doc(userId)
return await queryFirestore(ref)
}
关于javascript - 直接在 Google Firestore 中获取 DocumentId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51886626/