如何检查文档中是否存在字段

How to check if the fields exist in a document

我有一个用户集合,我正在尝试搜索名字和姓氏是否存在,如果不存在,我只想显示它不存在的消息。我试过了,但它不起作用,它会 运行 catch 短语。

 async function readUser() {
    try {
      const q = query(
        collection(db, "users"),
        where("firstName", "==", firstName),
        where("lastName", "==", lastName)
      );
      const docSnap = await getDoc(q);

      if (docSnap.exists()) {
        console.log("Document data:", docSnap.data());
      } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
      }

    } catch (err) {
      console.log("cannot add user");
    }
  } 

首先,如果您正在执行查询,您应该使用 getDocs()getDoc() 仅用于获取单个文档。然后你会得到一个 QuerySnapshot that does not have a exists property. If you can instead check if the query returned an empty response (i.e. no matching document) using empty 属性。尝试重构文档,如下所示:

async function readUser() {
  try {
    const q = query(
      collection(db, "users"),
      where("firstName", "==", firstName),
      where("lastName", "==", lastName)
    );

    const querySnap = await getDocs(q);

    if (querySnap.empty) {
      console.log("No matching document, name available");
    } else {
      console.log("Name found", querySnap.docs.map((d) => d.data()));
    }
  } catch (err) {
    console.log("cannot add user");
  }
}