比较更新 Firestore 字段的方法

Comparing approaches for updating Firestore fields

寻找建议来优化更新 Firestore 数据库字段以响应同一文档中不同字段的比较的机制。该机制用于用户提供验证码,然后后端进程将文档标记为已验证。

选项 1) 运行 Node.js 环境 - 这有一个 Collection Snapshot 寻找更新,然后比较特定的文档字段值,如果它们匹配则更新 'verified' 字段。

console.log("listen.js - listening for order submissions in the db...")
db.collection(dbPath)
  .where('code', '!=', 'XXXX')
  .onSnapshot((querySnapshot) => {
    var items = [];
    var index = 0;
    console.log("Listening ... dbPath = ", dbPath)
    querySnapshot.forEach((doc) => {

      const ref = db.collection(dbPath).doc(doc.id);
      if (doc.data().code === doc.data().resp) {
        ref.update({ verified: true })
          .then((res) => {
            console.log("Verified resp:", res)
          })
      }
    });
  });

选项 2)使用 Firebase Cloud Functions - 似乎没有办法监控单个字段,因此检查整个文档的任何更新,然后提取整个文档数据以比较所需字段然后对 'verified' 字段执行更新

  exports.verify = functions.firestore
  .document('contacts/{bid}/orders/{oid}')
  .onUpdate((change, context) => {

    const { userId, bid, oid } = context.params;
    console.log("Params:", context.params)

    const newValue = change.after.data() || {};
    if (newValue.code === newValue.resp) {
     
      console.log("Code verified")
      // Update verified flag
      const document = firestore.doc(`contacts/${bid}/orders/${oid}`);
      document.update({
        verified: true
      });
      return "Verified"
    } else {
      // perform desired operations ...
      console.log("Code not verified...")
      return "No"
    }

  });

问题是以下哪个选项更好: a) 流程和资源效率 - Cloud Functions 选项提取整个文档,然后对所需字段进行比较。 Node 环境似乎可以对更少的数据进行更精确的查询。 b) Cost/environment 开销 - 是一个相对较小的节点环境 运行 这个过程比 Cloud Function 运行 和验证文档成本更低。显然,这可能取决于操作(和处理的订单)的数量,因此可能会增加使用率。

我知道有几个 'it-depends' 答案,但是对于 Cloud Function 与专用 Node.js 进程环境,是否有任何一般性想法。随着 load/usage 的增加,效率和成本会如何变化?

谢谢。

只是为了说清楚。在这两种情况下,如果只有其中一个被更改触发,您将阅读整个 document。因此,如果您观察到它们都会给您相同的阅读量。

关于性能,我“个人”会坚持使用 Cloud Functions。您的场景听起来非常适合它。就像 Cloud Functions 的用途一样。

如果您有 运行 的免费后端资源并保留 node.js 解决方案并 运行 进行、更新、保护等...您可以通过以下方式节省一些钱减少 Cloud Functions 触发器数量。但是当听你的场景时,听起来不像是经常发生而应该让你害怕的事情。

我会更害怕不断收听的收集侦听器检查更改并保持它并运行宁 24/7。