Jack Wilson
Jack Wilson

Reputation: 6245

Cloud Firestore: TypeError: Cannot read property 'ref' of undefined

Cloud Firestore: TypeError: Cannot read property 'ref' of undefined

I'm using Cloud Functions to update the comments number in the parent collection of Cloud Firestore, so when a comment added the Cloud Functions can automatically update the comment number.

exports.updateCommentNumbers = functions.firestore
.document('postlist/{postlistId}/comments/{commentsID}')
.onCreate(event => 
{
    const collectionRef = event.after.ref.parent;
    const countRef = collectionRef.parent.child('comment_number');

    //const previousValue = event.data.previous.data();
    let increment;
    if (event.after.exists() )
    {
        increment = 1;
    }
     else 
    {
        return null;
    }

    return countRef.transaction((current) => 
    {
        return (current || 0) + increment;
    }).then(() => 
    {
        return console.log('Comments numbers updated.');
    });
});

I got error which I don't understand. Could you tell me what's wrong?

TypeError: Cannot read property 'ref' of undefined at exports.updateCommentNumbers.functions.firestore.document.onCreate.event (/user_code/index.js:46:35) at Object. (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27) at next (native) at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71 at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12) at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36) at /var/tmp/worker/worker.js:716:24 at process._tickDomainCallback (internal/process/next_tick.js:135:7)

Upvotes: 1

Views: 1809

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

As show in this upgrade guide the signature of Cloud Functions for Firebase has changes when it switched to v1.0.

If you used this before v1.0:

exports.dbWrite = functions.firestore.document('/path').onWrite((event) => {
  const beforeData = event.data.previous.data(); // data before the write
  const afterData = event.data.data(); // data after the write
});

It now is:

exports.dbWrite = functions.firestore.document('/path').onWrite((change, context) => {
  const beforeData = change.before.data(); // data before the write
  const afterData = change.after.data(); // data after the write
});

Instead of rewriting the code for you, I recommend you update it based on that documentation, or check where you got the code from to see if there's an updated version.

Upvotes: 2

Related Questions