【问题标题】:Check if Firestore document exists and return boolean检查 Firestore 文档是否存在并返回布尔值
【发布时间】:2021-11-01 03:13:20
【问题描述】:

我想创建一个实用函数,根据集合中是否存在 Firestore 文档返回 truefalse

下面是我最初写的,但它返回一个承诺而不是布尔值。

async function docExists(docName, docId) {
  const docRef = db.collection(docName).doc(docId);

  await docRef.get().then((docSnapshot) => {
    if (docSnapshot.exists) {
      return true
    } else {
      return false
    }
  });
}

有没有办法让它返回一个布尔值,或者这只是解决问题的错误方法?

【问题讨论】:

  • 您返回的是您传递给.then() 的回调函数,而不是docExists 函数。 docExits 函数不返回任何内容,但由于它是 async,因此它返回一个空承诺。用 return docSnapshot.exists; 替换你的 if 块(你不需要)并在 await 之前放一个 return

标签: javascript firebase google-cloud-firestore promise


【解决方案1】:

没有必要像您在问题中那样混合使用 await.then 语法。这应该足够了:

async function docExists(docName, docId) {
  const docRef = db.collection(docName).doc(docId);

  let docSnapshot = await docRef.get();
  
  if (docSnapshot.exists) {
    return true;
  } else {
    return false;
  }
}

或者,通过使用promise chaining,您应该能够简单地在问题中的原始await docRef.get().then(...) 之前添加return 关键字。

【讨论】:

  • 那个if块可以换成return docSnapshot.exists;
【解决方案2】:

一个简单的衬里可以是:

const docExists = async (docName, docId) => (await db.collection(docName).doc(docId).get()).exists

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 2021-11-23
    • 2021-07-22
    相关资源
    最近更新 更多