如何从Firestore查询快照中获取特定的文档数据? [英] How can I get specific document data from firestore querysnapshot?

查看:76
本文介绍了如何从Firestore查询快照中获取特定的文档数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个函数中有一个querysnapshot. 并希望将整个查询快照带到另一个函数(functionTwo). 在functionTwo中,我想在没有forEach的querysnapshot中获取特定文档.具体文档可以根据大小写进行更改.

I got a querysnapshot in a function. And want to bring the whole querysnapshot to another function (functionTwo). In functionTwo, I want to get a specific document in the querysnapshot WITHOUT forEach. The specific doc can be changed by different case.

ref_serial_setting.get()
    .then(querysnapshot => {
      return functionTwo(querysnapshot)
    })
    .catch(err => {
      console.log('Error getting documents', err)
    })


let functionTwo = (querysnapshot) => {
  // getting value

  const dataKey_1 = "dataKey_1"

  // Tried 1
  const value = querysnapshot.doc(dataKey_1).data()

  // Tried 2
  const value = querysnapshot.document(dataKey_1).data()

  // Tried 3 (Put 'data_name': dataKey_1 in that doc)
  const value = querysnapshot.where('data_name', '==', dataKey_1).data()
}

所有这些尝试的结果都不是函数.

The result are all these trying are not a function.

如何从querysnapshot获取特定的文档数据?

How can I get specific document data from querysnapshot??

有没有简单的方法可以将querysnapshot更改为JSON?

Is there any easy method to change the querysnapshot to JSON?

推荐答案

您可以使用QuerySnapshotdocs属性来获取文档快照的数组.之后,您将不得不遍历获取文档快照的数据以查找您的文档.

You can get an array of the document snapshots by using the docs property of a QuerySnapshot. After that you'll have to loop through getting the data of the doc snapshots looking for your doc.

const docSnapshots = querysnapshot.docs;

for (var i in docSnapshots) {
    const doc = docSnapshots[i].data();

    // Check for your document data here and break when you find it
}

或者,如果您实际上不需要完整的QuerySnapshot,则可以使用where函数之前对查询调用get来应用过滤器对象:

Or if you don't actually need the full QuerySnapshot, you can apply the filter using the where function before calling get on the query object:

const dataKey_1 = "dataKey_1";    
const initialQuery = ref_serial_setting;
const filteredQuery = initialQuery.where('data_name', '==', dataKey_1);

filteredQuery.get()
    .then(querySnapshot => {
        // If your data is unique in that document collection, you should
        // get a query snapshot containing only 1 document snapshot here
    })

    .catch(error => {
        // Catch errors
    });

这篇关于如何从Firestore查询快照中获取特定的文档数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆