How can I get specific document data from firestore querysnapshot?

前端 未结 3 399
我在风中等你
我在风中等你 2020-12-17 03:09

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 qu

相关标签:
3条回答
  • 2020-12-17 03:40

    Theres an easy way to do this, each QuerySnapshot has a property docs which returns an array of QueryDocumentSnapshots. See QuerySnapshot documentation.

    let citiesRef = db.collection('cities');
    let query = citiesRef.where('capital', '==', true).get().then(snapshot => {
      snapshot.docs[0]; // => returns first document
    });
    
    0 讨论(0)
  • 2020-12-17 03:58
    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

    0 讨论(0)
  • 2020-12-17 03:59

    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
        });
    
    0 讨论(0)
提交回复
热议问题