Adeojo Kiibati
Adeojo Kiibati

Reputation: 35

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

I recently started playing with cloud functions and I am getting this error:

> 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)

and this is my code

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);
    });

The onCreate function triggers at the right time and the problem is just the error. I have done my research and couldn't figure it out. I hope I can get some help.

Thanks in advance :).

Upvotes: 0

Views: 1436

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317750

onCreate functions receive a DocumentSnapshot type argument as its first parameter. It looks like your function is not actually expecting that. Since you're trying to use a property called after, it looks like your code is expecting a Change type argument, which will never be the case for onCreate events. Change type objects are delivered to onUpdate or onWrite events only so you can detect the before and after states of a document.

If you want the data from a newly created document in an onCreate type trigger, you should code like this:

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

Upvotes: 3

Related Questions