云功能错误"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

相关内容

最新更新