【问题标题】:Cloud functions, create document if there is no document else send error云功能,如果没有文档则创建文档,否则发送错误
【发布时间】:2021-04-11 09:37:07
【问题描述】:

我正在尝试创建一个系统,如果用户请求优惠券

  • 它将检查用户是否已经请求了优惠券
  • 那么它应该在一个集合中作为一个文档。
  • 如果没有文档,它将生成一个文档。

所以我期望的是,如果我运行代码并且集合中有一个文档,它应该取消操作吗?
但事实并非如此。它只是更新文档字段 createdAt 和 qrCodeId。

export const addCoupon = functions.https.onCall(async (data, context) => {
  const key = nanoid();
  const today = admin.firestore.FieldValue.serverTimestamp();
  const uid = context.auth!.uid;
  const couponRef = db
    .collection("kuponger")
    .doc("newCoupons")
    .collection(data.school)
    .doc(uid);
  const doc = await couponRef.get();

  if (!context.auth) {
    throw new functions.https.HttpsError(
      "failed-precondition",
      "Du måste vara inloggad"
    );
  }

  if (!doc.exists) {
    couponRef
      .set({
        createdAt: today,
        createdBy: uid,
        qrCodeId: key,
      })
      .catch((error) => {
        throw new functions.https.HttpsError("unknown", error);
      });
  } else {
    throw new functions.https.HttpsError("already-exists", "finns redan");
  }
});

它看起来应该可以工作,但是当我尝试运行它并且集合中已经存在一个文档时,它会更新文档而不是取消操作。

你能帮帮我吗?

如果您需要更多信息,请发表评论。

【问题讨论】:

    标签: node.js firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    在这一行:

    const uid = context.auth!.uid;
    

    你想使用:

    const uid = context.auth?.uid;
    

    完成可选链接。但是,我认为最好先移动“前置条件代码”,在这种情况下,不需要可选链接。

    export const addCoupon = functions.https.onCall(async (data, context) => {
      if (!context.auth) {
        throw new functions.https.HttpsError(
          "failed-precondition",
          "Du måste vara inloggad"
        );
      }
    
      const key = nanoid();
      const today = admin.firestore.FieldValue.serverTimestamp();
      const uid = context.auth.uid;
      const couponRef = db
        .collection("kuponger")
        .doc("newCoupons")
        .collection(data.school)
        .doc(uid);
      const doc = await couponRef.get();
    
      if (!doc.exists) {
        couponRef
          .set({
            createdAt: today,
            createdBy: uid,
            qrCodeId: key,
          })
          .catch((error) => {
            throw new functions.https.HttpsError("unknown", error);
          });
      } else {
        throw new functions.https.HttpsError("already-exists", "finns redan");
      }
    });
    
    

    【讨论】:

    • 感谢您的回复,但即使不应该更新文档,它仍然会更新文档。您知道这是怎么发生的吗?
    【解决方案2】:

    我通过重新安装 firebase 功能并重新初始化它来解决问题。

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 2019-09-09
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 2018-09-13
      • 2021-02-24
      • 2021-09-13
      相关资源
      最近更新 更多