javascript - Firebase 实时数据库 JS 错误:Reference.set 失败
问题描述
我在云功能中收到此错误
Error: Reference.set failed: First argument contains NaN in property 'server.saving-data.fireblog.history.newid.Id'
at validateFirebaseData (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:1497:15)
at /workspace/node_modules/@firebase/database/dist/index.node.cjs.js:1534:13
at each (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:554:13)
at validateFirebaseData (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:1517:9)
at /workspace/node_modules/@firebase/database/dist/index.node.cjs.js:1534:13
at each (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:554:13)
at validateFirebaseData (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:1517:9)
at validateFirebaseDataArg (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:1475:5)
at Reference.set (/workspace/node_modules/@firebase/database/dist/index.node.cjs.js:13928:9)
at /workspace/index.js:44:20
我输入的js代码如下
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
var db = admin.database();
var ref = db.ref("server/saving-data/fireblog");
exports.addHistory = functions.database.ref('issue/{id}').onCreate(async (snapshot, context) => {
const val = snapshot.val();
var lastid;
return admin.database().ref('history').orderByChild("Id").limitToLast(1).on("child_added", function (snapshot) {
snapshot.forEach(function (data) {
lastid = data.val().Id;
});
const timeElapsed = Date.now();
const today = new Date(timeElapsed);
var datetime=today.toUTCString();
var newid = lastid + 1;
var usersRef = ref.child("history");
usersRef.set({
newid: {
Lamp: val.Id,
Reported: datetime,
Completed:"",
Status:"Pending",
AssignedTo:"",
Id:newid
}
});
});
});
这是我需要添加记录的地方所以我在当前情况下得到的最后一个 Id 是 2 并以 1 为增量增加 3 并使用键 3 添加一条新记录
规则已定
解决方案
由于您正在读取history
,并且已经使用单个子节点调用child_added
了snapshot
回调中的 。这意味着不需要snapshot.forEach()
.
我还建议使用once
而不是在on
这里,因为您不想在读取一次值后保持侦听器处于活动状态。
最后,您还需要返回 promise fromusersRef.set()
以确保 Cloud Function 在写入数据库完成之前不会中止。
全部结合起来,看起来像这样:
return admin.database().ref('history').orderByChild("Id").limitToLast(1).once("child_added")
.then(snapshot => {
lastid = snapshot.val().Id;
const timeElapsed = Date.now();
const today = new Date(timeElapsed);
var datetime=today.toUTCString();
var newid = lastid + 1;
var usersRef = ref.child("history");
return usersRef.set({
newid: {
Lamp: val.Id,
Reported: datetime,
Completed:"",
Status:"Pending",
AssignedTo:"",
Id:newid
}
});
});
推荐阅读
- reactjs - 启动 server.js 文件时,登陆页面未显示在 Reactjs /Express 中
- flutter - 如何在导航到路线之前进行验证?
- asp.net-web-api - 如何使用 Azure AD 对企业用户以及单页应用程序中的外部用户进行身份验证?
- c# - 从对象列表创建一个 csv 文件 C#
- sql-server - 无法从 Ubuntu SQL Server Express 连接到 Amazon AWS SQL Server Express 数据库
- list - 查询地图列表的元素,并更新 dart 中的一个元素
- sql-server - 用相同的字符串替换替换多个字符串
- wordpress - 如何在 Wordpress 中显示类似 Google 财经的数据
- javascript - 使用 jQuery 淡入淡出文本
- javascript - 使用次要条件对数组进行排序