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

Firebase实时数据库报错:TypeError: (0, _database.where) is not a function

问题解决:TypeError: (0, _database.where) 不是一个函数

错误原因

你混淆了Firebase实时数据库(Realtime Database)与Firestore的API。where是Firestore的查询方法,实时数据库中实现字段过滤,需要用orderByChild结合equalTo的组合写法。

修正步骤

  1. 调整导入语句:移除where,导入实时数据库所需的orderByChild和equalTo
  2. 修改查询逻辑:替换原where写法为实时数据库的查询语法
  3. 配置数据库索引:在实时数据库规则中为users/email字段配置索引,否则查询会失败

修正后的代码

import { ref, get, set, query, orderByChild, equalTo} from 'firebase/database';

useEffect(() => {
  const writeToDatabase = () => {
    if (location && location.coords && UserDataFromGoogleAuth) {
      const usersRef = ref(database, 'users');
      const email = UserDataFromGoogleAuth.email;
      if (email) {
        // 替换为实时数据库的查询方式
        const userQuery = query(usersRef, orderByChild('email'), equalTo(email));
        get(userQuery).then((snapshot) => {
          let uuid;
          if (snapshot.exists()) {
            // 获取第一个匹配的用户ID(假设邮箱唯一)
            uuid = Object.keys(snapshot.val())[0];
          } else {
            uuid = uid();
          }
          const userRef = ref(database, `/users/${uuid}`);
          const userData = {
            id: uuid,
            name: UserDataFromGoogleAuth.displayName,
            email: email,
            includedKids: 0,
            isSubscribed: false,
            long: location.coords.longitude,
            lat: location.coords.latitude,
            online: props.online,
            profilePicture: UserDataFromGoogleAuth.photoURL,
          };
          set(userRef, userData);
        }).catch(error => {
          console.log(error);
        });
      }
    }
  };
  writeToDatabase();
}, [UserDataFromGoogleAuth, location, props.online]);

数据库索引配置

在Firebase控制台的实时数据库规则中,添加以下索引配置:

{
  "rules": {
    "users": {
      ".indexOn": ["email"]
    }
  }
}

额外说明

  • 实时数据库查询会返回所有匹配条件的节点,这里默认邮箱是唯一的,因此取第一个匹配的ID即可
  • 若要严格保证邮箱唯一性,建议在数据库规则中添加验证逻辑,避免重复邮箱的用户被创建

内容的提问来源于stack exchange,提问作者Mahmoud Hlal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:36:30