Javascript Firestore按字段值检索单个文档并更新

Javascript Firestore按字段值检索单个文档并更新,javascript,firebase,google-cloud-firestore,Javascript,Firebase,Google Cloud Firestore,我试图通过字段值检索单个文档,然后更新其中的字段。 当我执行.where(“uberId”、“==”、'1234567')时,我将获得所有字段uberId与1234567匹配的文档。 我确信只有一份这样的文件。但是,我不想使用uberId作为文档的ID,否则我可以通过ID轻松搜索文档。是否有其他方法通过字段ID搜索单个文档 到目前为止,通过阅读文档,我可以看到: const collectionRef = this.db.collection("bars"); const m

我试图通过字段值检索单个文档,然后更新其中的字段。 当我执行
.where(“uberId”、“==”、'1234567')
时,我将获得所有字段
uberId
1234567
匹配的文档。 我确信只有一份这样的文件。但是,我不想使用uberId作为文档的ID,否则我可以通过ID轻松搜索文档。是否有其他方法通过字段ID搜索单个文档

到目前为止,通过阅读文档,我可以看到:

const collectionRef = this.db.collection("bars");
const multipleDocumentsSnapshot = await collectionRef.where("uberId", "==",'1234567').get();
然后我想我可以执行
constdocumentsnapshot=documentsSnapshot.docs[0]
来获取唯一的现有文档引用

但我想用以下内容更新文档:

documentSnapshot.set({
  happy: true
}, { merge: true })

我得到一个错误,
属性“set”在类型“QueryDocumentSnapshot”上不存在。

虽然您可能知道一个事实,即只有一个文档具有给定的
uberId
值,但API无法知道这一点。因此,API为任何查询返回相同的类型:a
QuerySnapshot
。您需要在该快照中循环结果以获取文档。即使只有一个文档,您也需要该循环:

const querySnapshot = await collectionRef.where("uberId", "==",'1234567').get();
querySnapshot.forEach((doc) => {
  doc.ref.set(({
    happy: true
  }, { merge: true })
});

代码中缺少的是
.ref
:您无法更新
文档快照
/
查询文档快照
,因为它只是数据库中数据的本地副本。因此,您需要在其上调用
ref
,以获取对数据库中该文档的引用

async function getUserByEmail(email) {
  // Make the initial query
  const query = await db.collection('users').where('email', '==', email).get();

   if (!query.empty) {
    const snapshot = query.docs[0];
    const data = snapshot.data();
  } else {
    // not found
  }

}