【问题标题】:"documentRef" is not a valid DocumentReference showing while updating a field“documentRef”不是在更新字段时显示的有效 DocumentReference
【发布时间】:2019-07-22 21:09:21
【问题描述】:

我正在尝试计算通知的数量。我的数据库结构是 Users/userId/notification/doc。我想跟踪通知的编号。我的代码是

notificationCount: async (change,context) => {
        const countRef=db.collection("Users").doc(context.params.userID);
        let increment;
        if (change.after.exists && !change.before.exists) {
          increment = 1;
        } else if (!change.after.exists && change.before.exists) {
          increment = -1;
        } else {
          return null;
        }

    return db.runTransaction((transaction) => {
      return transaction.get(countRef).then((sfDoc) => {
        if (!sfDoc.exists) {

          return transaction.set({
            notifications: 0
          }, { merge: true });
        } else {
          var newNotification = sfDoc.data().population + increment;
          return transaction.set({
            notifications: newNotification
          });
        }

      });
    }).then(() => {
      console.log("Transaction successfully committed!");
      return null;
    }).catch((error) => {
      console.log("Transaction failed: ", error);
    });

  }

但我遇到了错误

    at Object.validateDocumentReference (/srv/node_modules/@google-cloud/firestore/build/src/reference.js:1810:15)
    at WriteBatch.set (/srv/node_modules/@google-cloud/firestore/build/src/write-batch.js:241:21)
    at Transaction.set (/srv/node_modules/@google-cloud/firestore/build/src/transaction.js:182:26)
    at transaction.get.then (/srv/counter.js:71:30)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

【问题讨论】:

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


    【解决方案1】:

    你的错误在两个地方:

          return transaction.set({
            notifications: 0
          }, { merge: true });
    

    这里:

          return transaction.set({
            notifications: newNotification
          });
    

    在调用transaction.set() 时,您必须调用特定的文档以进行更新。正如您从链接的 API 文档中看到的那样,set() 的第一个参数必须是 DocumentReference 类型的对象,但您传递的是一个普通的旧 JavaScript 对象。也许您打算使用从同一事务中读取的文档引用 countRef

          return transaction.set(countRef, {
            notifications: newNotification
          });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多