javascript - 无法使用 Node.js 解析 Firebase 的快照
问题描述
我有一个查询,它返回快照;
ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {})
当我用 ; 打印快照时
console.log(snapshot.val());
打印如下;
{'-LBHEpgffPTQnxWIT4DI':
{
date: '16.05.2018',
first: 'let me in',
index: 1,
second: 'let others in'
}
},
我需要记录起息日,即此快照的第一个值。
我试过了;
childSnapshot.val()["first"]
childSnapshot.val()["date"]
或者
childSnapshot.child.('first')
childSnapshot.child.('date')
但没有成功。
请指出我正在做的错误......
我的完整代码如下;
var indexRef = db.ref("/LastIndex/");
var ref = db.ref("/Source/")
indexRef.on("value", function(indexSnapshot) {
console.log(indexSnapshot.val());
var currentIndex = indexSnapshot.val()
ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {
console.log(snapshot.val());
if(snapshot !== null) {
snapshot.forEach(function (childSnapshot) {
if(childSnapshot !== null) {
var newRef = db.ref("/ListTest/");
var key = newRef.push({
"firstLanguageWord": childSnapshot.val()["first"] ,
"secondLanguageWord": childSnapshot.val()["second"] ,
"wordType": childSnapshot.val()["type"],
"date": childSnapshot.val()["date"],
"translateType": childSnapshot.val()["transType"]
});
currentIndex++;
indexRef.set(currentIndex);
}
});
}
});
BR,
埃尔登
解决方案
根据您在下面的评论和对原始问题的更新进行更新:
如果您的代码看起来“无限迭代”,那是因为您在第一个查询中使用了 on() 方法。事实上,该on()
方法“在特定位置侦听数据更改”,如此处所述。
如果您只想查询一次引用,请改用该once()
方法。文档在这里。
以下是Query,因为您在Reference(以及方法)上调用该orderByChild()
方法。equalTo()
ref.orderByChild("index").equalTo(currentIndex)
如文档中所述:
即使查询只有一个匹配项,快照仍然是一个列表;它只包含一个项目。要访问该项目,您需要遍历结果:
ref.once('value', function(snapshot) { snapshot.forEach(function(childSnapshot) { var childKey = childSnapshot.key; var childData = childSnapshot.val(); // ... }); });
所以你应该这样做:
ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
console.log(childSnapshot.val().first);
console.log(childSnapshot.val().date);
});
});
推荐阅读
- python - 图形 - python 中带有闪电的下雨动画
- android - 约束布局中的中心视图
- linux-kernel - 内核恐慌:没有找到工作的初始化。尝试将 init= 选项传递给内核
- typo3 - TYPO3 8.7 图像高度不起作用
- angularjs - angularjs,uirouter - 在控制器更新时更新 ng-model?
- google-chrome-extension - chrome 扩展:在同一浏览器中为 gmail 的多个登录帐户存储“chrome 本地存储”变量
- jboss - 骆驼中过滤器和选择之间的区别
- sql - 来自光标的 Oracle 最后记录
- microsoft-graph-api - 如何在特定时间间隔内从收件箱阅读我的邮件或从特定电子邮件地址发送的邮件?
- batch-file - 进程无法访问文件,因为它正在被另一个程序使用