【问题标题】:Firestore retrieve single document by field value and updateFirestore 按字段值检索单个文档并更新
【发布时间】:2020-11-04 14:56:23
【问题描述】:

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

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

const collectionRef = this.db.collection("bars");
const multipleDocumentsSnapshot = await collectionRef.where("uberId", "==",'1234567').get();

那么我想我可以通过const documentSnapshot = documentsSnapshot.docs[0] 获取唯一现有的文档参考。

但是我想用这个来更新文档:

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

我收到一个错误Property 'set' does not exist on type 'QueryDocumentSnapshot<DocumentData>'

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

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

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

    您的代码中缺少.ref:您无法更新DocumentSnapshot/QueryDocumentSnapshot,因为它只是数据库中数据的本地副本。所以你需要在它上面调用ref来获取数据库中那个文档的引用。

    【讨论】:

      【解决方案2】:
      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
        }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2021-09-23
        • 1970-01-01
        • 1970-01-01
        • 2018-04-21
        • 1970-01-01
        • 2020-04-19
        • 1970-01-01
        • 2019-01-12
        • 2021-09-15
        相关资源
        最近更新 更多