云函数错误 "Cannot read property 'data' of undefined"

Cloud Function error "Cannot read property 'data' of undefined"

我最近开始使用云函数,但遇到此错误:

> TypeError: Cannot read property 'data' of undefined
>     at exports.createPost.functions.firestore.document.onCreate (/srv/index.js:15:37)
>     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)

这是我的代码

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

const ALGOLIA_APP_ID = "";
const ALGOLIA_ADMIN_KEY = "";
const ALGOLIA_INDEX_NAME = "Posts";

admin.initializeApp(functions.config().firebase);
//const firestore = admin.firestore;

exports.createPost = functions.firestore
    .document('User/{UserId}/Posts/{PostsID}')
    .onCreate( async (snap, context) => {
        const newValue = snap.after.data();
        newValue.objectID = snap.after.id;

        var client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_ADMIN_KEY);

        var index = client.initIndex(ALGOLIA_INDEX_NAME);
        index.saveObject(newValue);
    });

onCreate函数在正确的时间触发,问题只是错误。我已经完成了研究,但无法弄清楚。希望能得到一些帮助。

提前致谢:)。

onCreate 函数接收一个 DocumentSnapshot 类型参数作为它的第一个参数。看起来您的功能实际上并不期望如此。由于您正在尝试使用名为 after 的 属性,看起来您的代码需要一个 Change 类型参数,而 onCreate 事件永远不会是这种情况。 Change 类型对象仅传送到 onUpdateonWrite 事件,以便您可以检测文档的前后状态。

如果你想在 onCreate 类型的触发器中从新创建的文档中获取数据,你应该这样编码:

exports.createPost = functions.firestore
    .document('User/{UserId}/Posts/{PostsID}')
    .onCreate( async (snap, context) => {
        const newValue = snap.data();
        // use the document properties of newValue here