Firebase Realtime Database v9调用ServerValue.increment报undefined错误求助
问题原因
你使用的是Firebase 9 模块化版本的SDK,代码里混用了已经废弃的旧版命名空间式API:
firebase.database.ServerValue.increment是v8及更早版本的自增写法,v9中该方法改为单独导出的increment函数database().ref().update()同样是旧版语法,v9中使用单独导出的update方法完成更新操作- 之前尝试用admin调用报错404,是因为admin是服务端专用SDK,不能在前端网页代码中使用
解决方案
第一步:修改导入语句
在firebase-database的导入列表中新增increment和update两个方法:
import { set, ref, getDatabase, child, get, increment, update } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-database.js';
第二步:修正setPlayerCount函数逻辑
你无需先读取数据判断playerCount是否存在,increment本身是原子操作,字段不存在时会自动将值初始化为1,完全可以省略读操作避免竞态问题,修改后的函数如下:
function setPlayerCount() { const gameRef = ref(database, 'game/'); update(gameRef, { playerCount: increment(1) }).catch((error) => { console.error(error); }) }
完整修改后的game.js代码
import * as firebase from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js"; import { set, ref, getDatabase, child, get, increment, update } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-database.js'; // Your web app's Firebase configuration const firebaseConfig = { apiKey: "apiKey information", authDomain: "authDomain information", databaseURL: "databaseURL information", projectId: "projectId information", storageBucket: "storageBucket information", messagingSenderId: "messagingSenderId information", appId: "appId information", measurementId: "measurementId information" }; const app = firebase.initializeApp(firebaseConfig); const database = getDatabase(app); function setPlayerCount() { const gameRef = ref(database, 'game/'); update(gameRef, { playerCount: increment(1) }).catch((error) => { console.error(error); }) } // Display Start Button and increment player count let button = document.createElement('button'); button.innerHTML = "Start"; button.onclick = function () { setPlayerCount(); button.style.display = "none"; } document.body.appendChild(button);
内容的提问来源于stack exchange,提问作者user16620897
相关产品推荐
相关产品推荐

