How can I get specific document data from firestore querysnapshot?

大兔子大兔子 提交于 2020-01-23 12:05:33

问题


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.

How can I get specific document data from querysnapshot??

or

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


回答1:


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
}

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
    });



回答2:


let citiesRef = db.collection('cities');
let query = citiesRef.where('capital', '==', true).get()
  .then(snapshot => {
    if (snapshot.empty) {
      console.log('No matching documents.');
      return;
    }  

    snapshot.forEach(doc => {
      console.log(doc.id, '=>', doc.data());
    });
  })
  .catch(err => {
    console.log('Error getting documents', err);
  });

from https://firebase.google.com/docs/firestore/query-data/get-data



来源:https://stackoverflow.com/questions/50692218/how-can-i-get-specific-document-data-from-firestore-querysnapshot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!