You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Firebase Firestore Where查询获取用户文档内数据并实现搜索

问题描述

数据库结构

这是我的数据库结构,我想通过输入框搜索用户的displayName,并展示对应的数据。以下是我编写的代码:

const belgeRef = collection(db, "users"); // Belge referansını oluşturun
        
const sorgu = query(
  belgeRef,
  where("displayName", ">=", inputValue),
  where("displayName", "<=", inputValue + "\uf8ff")
);

getDocs(sorgu)
  .then((querySnapshot) => {
    const bulunanKullanicilar = [];
    querySnapshot.forEach((doc) => {
      const belgeVerileri = doc.data();
      const kullaniciAdi = belgeVerileri.data[0].displayName;
      console.log(belgeVerileri)
      bulunanKullanicilar.push(kullaniciAdi);
    });
    setVeriler(bulunanKullanicilar);
    
    console.log("Bulunan Kullanıcılar:", bulunanKullanicilar);
  })
  .catch((error) => {
    console.error("Hata:", error);
  });

我需要正确访问users集合下用户文档内的displayName数据。

修正方案

从数据库截图能看到,displayName是直接存在用户文档的顶层字段里,并没有嵌套在data数组中。所以代码里访问字段的方式错误,调整如下:

const belgeRef = collection(db, "users");
        
const sorgu = query(
  belgeRef,
  where("displayName", ">=", inputValue),
  where("displayName", "<=", inputValue + "\uf8ff")
);

getDocs(sorgu)
  .then((querySnapshot) => {
    const bulunanKullanicilar = [];
    querySnapshot.forEach((doc) => {
      const belgeVerileri = doc.data();
      // 直接从文档数据中读取displayName
      const kullaniciAdi = belgeVerileri.displayName;
      console.log(belgeVerileri)
      bulunanKullanicilar.push(kullaniciAdi);
    });
    setVeriler(bulunanKullanicilar);
    
    console.log("Bulunan Kullanıcılar:", bulunanKullanicilar);
  })
  .catch((error) => {
    console.error("Hata:", error);
  });

如果需要获取完整的用户文档数据(不止displayName),可以把包含文档ID的完整对象存入数组:

querySnapshot.forEach((doc) => {
  const kullanici = {
    id: doc.id,
    ...doc.data()
  };
  bulunanKullanicilar.push(kullanici);
});

内容的提问来源于stack exchange,提问作者Esat İnan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:57:24