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

Firebase报错Uncaught TypeError: db.ref is not a function求助

解决Firebase v9中Uncaught TypeError: db.ref is not a function错误

你遇到的问题是因为Firebase v9采用了模块化API,和旧版v8的命名空间写法完全不同,db.ref()这种链式调用在v9里已经被废弃,必须使用导入的独立工具函数来创建数据库引用。

具体修正步骤:

  1. 若需要分步构建路径,先确保导入child函数(已有ref的话,按需添加):

    import { getDatabase, ref, set, get, child } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-database.js";
    
  2. 将创建引用的代码替换为模块化写法,两种可选方式:

    • 方式一:直接在ref函数中指定完整路径(更简洁)
      const coleccionProductos = ref(db, "productos");
      
    • 方式二:用child函数分步拼接路径(适合动态生成路径的场景)
      const rootRef = ref(db);
      const coleccionProductos = child(rootRef, "productos");
      

修正后的完整代码示例:

// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js";
import { getDatabase, ref, set, get } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-database.js";

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "AIzaSyAalz5fFuOOG6_EZVFIO-hJRA2Sw1Yyg2A",
  authDomain: "lost-and-found-system-67568.firebaseapp.com",
  databaseURL: "https://lost-and-found-system-67568-default-rtdb.firebaseio.com",
  projectId: "lost-and-found-system-67568",
  storageBucket: "lost-and-found-system-67568.appspot.com",
  messagingSenderId: "32608786023",
  appId: "1:32608786023:web:6aea01187ecb53ce6a66c2"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
// 修正后的引用创建代码
const coleccionProductos = ref(db, "productos");
const bodyProductos = $("#bodyProductos").val();
// console.log(bodyProductos);

额外提醒:尽量给变量加上const或let声明,避免意外的全局变量污染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:46:04