【问题标题】:How can I write a cloud functions onUpdate Firestore to get values from a collection on update of another collection如何编写云函数 onUpdate Firestore 以在更新另一个集合时从集合中获取值
【发布时间】:2019-11-13 06:22:34
【问题描述】:

我有一组为用户映射的订单。这是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 ...
});

【问题讨论】:

  • 我已经用实际代码编辑了帖子。
  • 您应该查看firestore admin apithe documentation 中的Node.js 查询示例。这可用于从云函数内部进行查询。 This question 的情况与您的情况非常相似,可能会有用。确保您还小心返回承诺链(例如,您当前的消息调用没有这样做)。
  • 您是否收到错误消息,如果您收到错误消息,能否与我们分享。如果您遇到错误,您知道是在阅读时还是在写作时出错?

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


【解决方案1】:

我做了一个与你的架构相同的 firestore 数据库: users/{userID}/orders/{orderID}users/{userID}/tokens/{tokenID}

我用来触发应用的事件是: providers/cloud.firestore/eventTypes/document.update 上资源:users/{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是其他操作的一些代码sn-ps。

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 2020-08-10
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多