所以我有这个查询,目前收集了所有 materialName
等于黄金的数据。我想全部更改为 false。
// materialName = "gold" for example
database.ref('/app/posts').orderByChild('material').startAt(materialName).endAt(materialName).once('value', function (snapshot) {
const materials = snapshot.val();
})
我试过这样的:
database.ref('/app/posts').orderByChild('material').startAt(materialName).endAt(materialName).once('value', function (snapshot) {
database.ref('/app/posts').update({material: false});
})
我也试过这个:
const newData = Object.assign({}, materials, {material: false});
// but this updates outside of the post, result will be:
"posts" : {
"material": false,
"post-1503586" : {
"title": "sample title",
"material" : "gold"
},
"post-9172991" : {
"title": "sample title",
"material" : "silver"
}
}
示例 json:
"posts" : {
"post-1503586" : {
"title": "sample title",
"material" : "gold"
},
"post-9172991" : {
"title": "sample title",
"material" : "silver"
}
}
最佳答案
您需要遍历结果(因为可能有多个匹配节点)然后更新每个结果:
database.ref('/app/posts')
.orderByChild('material')
.equalTo(materialName)
.once('value', function (snapshot) {
snapshot.forEach(function(child) {
child.ref.update({material: false});
});
});
您还会注意到,我将您的 .startAt().endAt()
更改为 equalTo()
,它以更少的代码提供相同的结果。
关于javascript - firebase 通过 orderByChild 抓取然后更新结果键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45874969/