简体   繁体   中英

Easiest way to read field from Firestore document


I have been running in circles over this simple problem: I am trying to read a field in a Firestore document. I am looking for the most straightforward solution that gives me a const to work with.

const userId = context.params.userId;

const customer = admin.firestore()
        .collection('stripe_customers')
        .doc(userId)
        .collection('customer_info')
        .data('customer_id');

The cloud function log gives me this:

TypeError: admin.firestore(...).collection(...).doc(...).collection(...).data is not a function

Same error with

.data().customer_id;

Here is another option I tried:

const customerDoc = admin.firestore()
        .collection('stripe_customers')
        .doc(userId)
        .collection('customer_info')
        .doc('customer_object');

        const customer = customerDoc.get('customer_id');

        console.log(customer);

With this option, the console logs a pending promise. Not sure how to work with that.

I've been through more tries than I can count and have exhausted the documentation. If anyone knows how to do this in a straight forward way, please let me know.

Ok, the almost correct answer was the second one. I just had to await the promise. Here is the code for anyone who is interested:

let customerRef = admin.firestore()
            .collection('stripe_customers')
            .doc(userId)
            .collection('customer_info')
            .doc('customer_object');

        const customer = await customerRef.get()
          .then(doc => {
            return doc.data().customer_id;
          })
          .catch(err => {
            console.log('Error getting document', err);
          });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM