0
votes

I'm trying to query a Firestore Document to retrieve a single field after a onCreate function.

import * as functions from 'firebase-functions';
import admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

exports.logActivities = functions.firestore
.document("AccountLog/{docID}")
.onCreate(async (snap, context) => { 
    const newValues = snap.get('newBalace');

    console.log(newValues);



    const query = db.collection('iniAccounts');
    const querySnapshot = await query.get();
    const initialValues = querySnapshot.docs.map(document => (document.data()));

    console.log(initialValues);
});

The collection that i'm querying only has one document with 2 fields. When I execute the code above the "document.data()" retrieves all the fields and values for the document.

[ { cStartingBalance: '288',
    cStartingDate: '12/30/2019' } ]

The only field I need is the cStartingBalance. I have tried several solutions but none have retrieved just the cStartingBalance value.

Since the goal is to compare the newValues with the initialValues, is there a different approach that i should be taking? Any assistance would be appreciated.

2
I don't understand what you're trying to do here. Are you saying you're going to assume this query only ever returns one document, and you want a value in a field of that document? And there's never going to be 0 or 2 or more documents? Seems like you could pretty easily just reach into that one element of the initialValues array... - Doug Stevenson
Doug, you are correct the value i'm trying to retrieve is in a collection that will only have one document. Although i could retrieve the whole document, i could not figure out how to pull out that one value. @Peter-Haddad provided the code that eluded me. Thank you. console.log(initialValues[0].cStartingBalance); - G. H.
Collection queries are intended to get zero or more documents from a collection. If you only ever need one document, there's no need to make a query for it. Just call out the one document by its ID and get() it individually. - Doug Stevenson

2 Answers

0
votes

Your code will be more clear and concise if you just get() the single document by its known ID. For example:

const initialValues = await db.collection('iniAccounts').doc('document_id').get();
const data = initialValues.data()
if (!data) {
    // no document found - determine what you want to do
}
else {
    const cStartingBalance = initialValues.data().cStartingBalance;
}

This code assumes that you have a single document called 'document_id' in the in the 'iniAccounts' collection.

0
votes

When you query a document, it will retrieve everything inside that document. If you are getting this list and want to access cStartingBalance, then you can do:

console.log(initialValues[0].cStartingBalance);