“ documentRef”不是在更新字段时显示的有效DocumentReference

时间:2019-07-22 21:09:21

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

我正在尝试计算通知数量。我的数据库结构为 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)

1 个答案:

答案 0 :(得分: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
      });