我如何在onUpdate Firestore上编写云函数以在更新另一个集合时从集合中获取值

时间:2019-11-13 06:22:34

标签: firebase google-cloud-firestore google-cloud-functions

我有一个为用户映射的订单集合。格式为users/{userID}/orders/{orderID})。我需要一个函数,该函数会将本文档的onUpdate发送通知到保存在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 ...
});

1 个答案:

答案 0 :(得分:0)

我使用与您的架构相同的架构创建了一个Firestore数据库: users/{userID}/orders/{orderID}users/{userID}/tokens/{tokenID}

我用来触发应用程序的事件是: 资源上的providers/cloud.firestore/eventTypes/document.updateusers/{userID}/orders/{orderID}

这使我可以在订单集合中的任何文档有更新时执行该功能。

源代码位于三个文件中:

credentials.json::这是第二部分中将与firestore交互的服务帐户的登录信息。要根据自己的项目获取此文件,可以按照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);
  });
};

尤其是此代码仅将其获取的文档记录到控制台日志中,例如,如果要在第二部分here上执行其他操作,则获取文档的示例是其他操作的一些代码片段。 / p>

相关问题