简体   繁体   中英

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

I am trying to get a url property of a document by first running an if function to see whether another document has certain property

const functions = require("firebase-functions");

// The Firebase Admin SDK to access Firestore.
const admin = require("firebase-admin");
admin.initializeApp();

exports.writeToClay = functions
    .region("europe-west1")
    .firestore
    .document("/reviews/{documentId}")
    .onWrite((change, context) => {
      // Grab the current value of what was written to Firestore.
      const websiteId = change.before.data().websiteId;
      console.log("websiteID:", websiteId);
      if (change.after.data().code == "1") {
        const url = admin.firestore().collection(
            "websites"
        ).doc(websiteId).get().data().url;
        console.log("url:", url);
      }
    });

The get() returns a Promise and does not have data() method on it. Try refactoring the code as shown below and handle the promise:

exports.writeToClay = functions
  .region("europe-west1")
  .firestore
  .document("/reviews/{documentId}")
  .onWrite(async (change, context) => { // <-- async function
    const websiteId = change.before.data().websiteId;
    console.log("websiteID:", websiteId);

    if (change.after.data().code == "1") {
      // add await here
      const snap = await admin.firestore().collection("websites").doc(websiteId).get()
      const url = snap.data().url;
      console.log("url:", url);
    }

    return
  });

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