创建Firebase实时数据库引用时遇TypeError错误求助
解决Firebase实时数据库报错TypeError: db._checkNotDeleted is not a function及功能实现
核心错误原因
你遇到的TypeError: db._checkNotDeleted is not a function是因为没有正确初始化数据库实例:getDatabase是一个函数,你直接把函数本身传给了ref,而不是调用它获取数据库实例。正确的做法是调用getDatabase()(或传入初始化的app实例)来拿到数据库对象,再创建引用。
其他代码问题修正
除了这个错误,你的代码还有几个关键问题需要修复才能实现需求:
- 表单提交未阻止默认刷新行为
- 直接用
child()创建引用判断值是错误的,Firebase数据读取是异步操作,必须用get()方法获取实际数据 set()方法的语法错误,以及更新手机号计数时需要先读取当前值再累加- 未定义
db变量,导致后续ref(db, ...)报错
完整修正代码
HTML部分(无需修改)
<form method="post" id="frmContact"> <table style="width:50%"> <tr> <th></th> <th></th> </tr> <tr> <td><input type="text" id="cedula" name="cedula" placeholder="Cédula (tuya)" size="25" type="number" minlength="4" maxlength="10" required><br></td> <td><input type="text" id="nv" name="nv" placeholder="#v" size="2" type="number" minlength="1" maxlength="1" required></td> </tr> <tr> <td><input type="text" id="telefono" name="telefono" placeholder="Teléfono de tu conductor" size="25" type="number" minlength="10" maxlength="10" required><br></td> <td></td> </tr> <tr> <td><input type="submit" value="Envíar" name="submit"></td> <td></td> </tr> </table> </form>
JavaScript部分(修正后)
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.12.1/firebase-app.js"; const firebaseConfig = { apiKey: "...", authDomain: "...", databaseURL: "...", projectId: "...", storageBucket: "...", messagingSenderId: "...", appId: "..." }; const app = initializeApp(firebaseConfig); import { getDatabase, ref, set, get, child } from "https://www.gstatic.com/firebasejs/9.12.1/firebase-database.js"; // 正确初始化数据库实例和根引用 const db = getDatabase(app); const dbRef = ref(db); document.getElementById('frmContact').addEventListener('submit', async function(e) { // 阻止表单默认提交刷新行为 e.preventDefault(); const cedula = document.getElementById('cedula').value; const nv = document.getElementById('nv').value; const telefono = document.getElementById('telefono').value; const voucherKey = cedula + nv; const phoneKey = telefono; try { // 异步获取数据库中的voucher和手机号数据 const snapshot = await get(child(dbRef, `vouchers/${voucherKey}`)); const phoneSnapshot = await get(child(dbRef, `phoneNumber/${phoneKey}`)); const voucherValue = snapshot.exists() ? snapshot.val() : null; const phoneValue = phoneSnapshot.exists() ? phoneSnapshot.val() : null; // 验证逻辑 if (voucherValue === '1' && phoneValue !== null) { // 更新voucher为已使用(0) await set(ref(db, `vouchers/${voucherKey}`), '0'); // 更新手机号计数(转成数字累加后再存为字符串) const newPhoneCount = (parseInt(phoneValue) + 1).toString(); await set(ref(db, `phoneNumber/${phoneKey}`), newPhoneCount); window.alert(`Felicidades, tu viaje ha sido pagado con éxito a ${telefono}`); } else if (voucherValue === '0') { window.alert("Este voucher promocional ya fue redimido"); } else if (voucherValue === '1' && phoneValue === null) { window.alert("Este teléfono no está asociado a ningún conductor"); } else { window.alert("Este voucher promocional no es válido"); } // 重置表单 document.getElementById('frmContact').reset(); } catch (error) { console.error('操作出错:', error); window.alert("Ocurrió un error al procesar tu solicitud"); } });
关键修正点说明
- 数据库初始化:
const db = getDatabase(app);正确调用getDatabase获取数据库实例,再创建根引用dbRef - 异步数据读取:用
async/await配合get()方法异步获取数据,因为Firebase操作是异步的,不能同步判断引用 - 表单默认行为阻止:添加
e.preventDefault();避免提交后页面刷新 - 数据更新逻辑:更新手机号计数时,先把字符串转成数字累加,再转回字符串存储(匹配你数据库的字符串格式)
- 错误处理:添加
try/catch捕获操作中的异常,避免页面崩溃并给出提示
内容的提问来源于stack exchange,提问作者unconscious statistician
相关产品推荐
相关产品推荐

