【问题标题】:How to limit size of an array in Firestore on a write?如何在写入时限制 Firestore 中数组的大小?
【发布时间】:2023-03-09 12:44:01
【问题描述】:

有谁知道如何限制数组,以便在同一次写入中推入新项目并丢弃旧项目?

我猜这是不可能的,但它肯定会很方便。

                    // * Store notification
                    // Users collection
                    const usersCollection = db.collection('users').doc(uid).collection('notifications').doc();

                    // Write this notification to the database as well
                    await usersCollection.update({
                        count: admin.firestore.FieldValue.increment,
                        notifications: admin.firestore.FieldValue.arrayUnion({
                            'symbol': symbol,
                            'companyname': companyname,
                            'change': priceDifference,
                            'changeDirection': directionOperatorHandler,
                            'updatedPrice': symbolLatestPrice,
                            'timestamp': currentTimestamp,
                        })
                    });

用打字稿编写


或者,我正在考虑每周运行一个预定的云函数,以根据时间戳检查和修剪数组。

我使用数组来存储通知的原因是因为我期待大量的写入。

【问题讨论】:

  • 如果您从客户端运行它,您可以制定一个查找计数值的安全规则,也可以创建一个云函数,在更改时触发并保留计数值,如果您是在服务器端,你可以通过对计数值的 if 语句自己实现。
  • 谢谢安德烈,我会尝试 Doug 的建议,如果它不能满足我的需求,我可能会使用预定的云功能????

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


【解决方案1】:

对此没有简单的配置。您的代码应通过以下方式实现您的要求:

  1. 阅读文档
  2. 修改内存中的数组
  3. 检查大小是否在限制范围内
  4. 回写文档

【讨论】:

  • 好吧,是啊,我猜哈哈。以阅读为代价,这似乎是一个很好的解决方案。再次感谢道格!
猜你喜欢
  • 2012-05-13
  • 2019-07-19
  • 2021-08-05
  • 1970-01-01
  • 2019-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多