Pankaj
Pankaj

Reputation: 39

Trigger a function when a new document is created is not working

I have tried an increment counter example (https://github.com/firebase/functions-samples/tree/master/child-count) with Cloud Functions which is referencing Realtime Database, but not Firebase Firestore.

I am following firestore document and tried some changes. Still facing issue and not able to run this code for firestore new document. I am writing cloud function first time, and I'm not sure I've written this right.

   exports.countlikechange = functions.database.ref('/posts/{postid}/likes/{likeid}').onWrite(
async (change) => {
  const collectionRef = change.after.ref.parent;
  const countRef = collectionRef.parent.child('likes_count');

  let increment;
  if (change.after.exists() && !change.before.exists()) {
    increment = 1;
  } else if (!change.after.exists() && change.before.exists()) {
    increment = -1;
  } else {
    return null;
  }

  // Return the promise from countRef.transaction() so our function
  // waits for this async event to complete before it exits.
  await countRef.transaction((current) => {
    return (current || 0) + increment;
  });
  console.log('Counter updated.');
  return null;
});

I want to update count in parent document.

Upvotes: 1

Views: 762

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

You should review the documentation for Firestore triggers. What you're writing is a Realtime Database trigger, because the function declaration is functions.database. You'll want to use functions.firestore instead. You're also using Realtime Database APIs instead of Firestore APIs. Your final solution that uses Firestore will look almost completely different than what you have now.

Upvotes: 1

Related Questions