首页 > 解决方案 > Firestore 函数 Console.log

问题描述

我错过了什么?尝试使用 console.log() 调试 Firestore 功能。firestore 函数日志显示错误详细信息,但是我似乎无法让 console.log() 将调试消息添加到日志:

这是函数日志错误:

TypeError: Cannot read property 'document' of undefined
      at exports.updateIndex.functions.firestore.document.onCreate.event (/srv/index.js:13:36)
      at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:131:23)
      at /worker/worker.js:825:24
      at <anonymous>
      at process._tickDomainCallback (internal/process/next_tick.js:229:7)

下面是 index.js 中的函数代码:

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

const admin = require('firebase-admin');
admin.initializeApp();

exports.updateIndex = functions.firestore
.document('Documents/{Name}')
.onCreate(event => {

   const documentId = event.params.document.id;
    const id = this.document ? this.document.id : '';
    console.log("Update Index for Doc", document);

    const document = event.after.data();

    console.log("docId",documentId,"id",id);

    const searchableIndex = newFunction(document)

    const indexedDocument = { ...document, searchableIndex }

    const db = admin.firestore()

    return db.collection('Documents').doc(document.id).set(indexedDocument, { merge: true })

})

function newFunction(document) {
    return createIndex(document.Name);
}

function createIndex(document) {
    const arr = Name.toLowerCase().split('');
    const searchableIndex = {}
console.log("Creating Index");
    let prevKey = '';

    for (const char of arr) {
        const key = prevKey + char;
        searchableIndex[key] = true
        prevKey = key
    }
    console.log("Create docId",documentId,"id",id);
    return searchableIndex
}

感谢您的任何想法!

标签: javascriptfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


你没有进入console.log你的代码在这一行中断的原因:

const id = this.document ? this.document.id : '';

由于找不到this,它会尝试设置this.document.id并崩溃。

所以对于你的具体问题,console.log按照你的想法工作,只要确保你的代码首先到达那个日志,你可以在错误行之前移动日志,你应该得到它

exports.updateIndex = functions.firestore
.document('Documents/{Name}')
.onCreate(event => {

   const documentId = event.params.document.id;

    /*********
     HERE IT WILL WORK
    ********/
    console.log(documentId) // Cool!

    const id = this.document ? this.document.id : ''; // ERROR LINE
    console.log("Update Index for Doc", document);

    const document = event.after.data();

    console.log("docId",documentId,"id",id); // WONT WORK

    const searchableIndex = newFunction(document)

    const indexedDocument = { ...document, searchableIndex }

    const db = admin.firestore()

    return db.collection('Documents').doc(document.id).set(indexedDocument, { merge: true })

})

您需要弄清楚的另一件事是this指的是什么?我认为你有一个概念错误


推荐阅读