0

I have a collection of orders mapped for a user. Which is in users/{userID}/orders/{orderID}) format. I need a function which onUpdate to this document sends a notification to an array of tokens saved in users/{userID}/tokens

exports.modifyUserCart = functions.firestore
    .document('users/{userID}/orders/{orderID}')
    .onUpdate((change, context) => {

    const document = change.after.exists ? change.after.data() : null;

    console.log(document.order_id)

    // document.order_id . "This prints correctly"

    // The tokens to be added to an array are in (users/{userID}/tokens). How                       
    // do I get the tokens from the collection of tokens

    var tokens = [] //array of tokens

    var message = {
        notification: {
            title: 'Get an upfront discount',
            body: "Clear your items in cart in the next hour to get an upfront
                discount of $100"
        },
        token: tokens
    };

    admin
      .messaging()
      .send(message)
      .then((response) => {
          // Response is a message ID string.
          console.log('Successfully sent message:', response);
      })
      .catch((error) => {
          console.log('Error sending message:', error);
      });
      // perform desired operations ...
});
Community
  • 1
  • 1
  • I have edited the post with actual code. – srinivas001 Nov 13 '19 at 09:19
  • You should look at the [firestore admin api](https://firebase.google.com/docs/reference/admin/node/admin.firestore) and the Node.js query examples in [the documentation](https://firebase.google.com/docs/firestore/query-data/queries). This can be used to make a query from inside of a cloud function. [This question](https://stackoverflow.com/q/58594212/3399890) has a very similar situation to yours and may be useful. Make sure you are also careful to return the promise chain (e.g. you're not doing that with your current messaging call). – robsiemb Nov 13 '19 at 15:19
  • are you getting an error message, and if you are getting one could you share it with us. And if you are getting an error do you know if its while reading or while writing? – Soni Sol Dec 11 '19 at 02:52

1 Answers1

0

I did a firestore database with the same architecture as yours: users/{userID}/orders/{orderID} and users/{userID}/tokens/{tokenID}

The event I used to trigger the app is: providers/cloud.firestore/eventTypes/document.update on the resource: users/{userID}/orders/{orderID}

this allowed me that the function executed when there was an update on any document in orders collections.

The sourcecode is in three files:

credentials.json: which is the login info for the service account that will interact with firestore in the second part. to get this file for your own projec you can follow here

package.json:

{
  "name": "sample-firestore",
  "version": "0.0.1",
  "dependencies": {
    "@google-cloud/firestore": "^2.6.1",
    "firebase-admin": "^8.8.0"
  }

}

index.js:

/**
 * Triggered by a change to a Firestore document.
 *
 * @param {!Object} event Event payload.
 * @param {!Object} context Metadata for the event.
 */
exports.helloFirestore = (event, context) => {
  const resource = context.resource;
  // log out the resource string that triggered the function
  console.log('Function triggered by change to: ' +  resource);
  // now log the full event object
  console.log(JSON.stringify(event));
  console.log("Doc Modified");
  const document = event.value.name;
  console.log(document);
  //ended know which document was modified

  //starting GET second collection

  const Firestore = require('@google-cloud/firestore');

  const db = new Firestore({
    projectId: '[YOUR_PROJECT_ID]',
    keyFilename: 'credential.json'
  });

  console.log(JSON.stringify(db));

  var str = document.split("/");
  console.log(str);
  console.log(str[6]);

  db.collection('users').doc(str[6]).collection('tokens').get()
  .then((snapshot) => {
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
  })
  .catch((err) => {
    console.log('Error getting documents', err);
  });
};

this code in particular only logs the documents it gets to the console log, as an example of getting the documents if you want to perform other operations on the second part here are some code snippets of other operations.

Soni Sol
  • 2,367
  • 3
  • 12
  • 23