【问题标题】:Trying to update value of a reference when onWrite?尝试在 onWrite 时更新引用的值?
【发布时间】:2017-07-28 18:55:46
【问题描述】:
当 /mystuff 中有写入时,我正在尝试更新 /myotherstuff 的值。但是下面的代码并没有这样做。我应该改变什么?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.myFunction = functions.database.ref('/mystuff')
.onWrite(event => {
admin.database().ref('/myotherstuff').update(null);
});
【问题讨论】:
标签:
javascript
firebase
google-cloud-functions
【解决方案1】:
尝试类似的方法:
exports.myFunction = functions.database.ref('/mystuff').onWrite(event => {
return admin.database().ref('/myotherstuff').set(null);
});
与set() 方法相反,update() 可用于选择性地仅更新当前位置的引用属性(而不是替换当前位置的所有子属性)。
在您的情况下,您可以删除孩子,而不是设置为 null:
exports.myFunction = functions.database.ref('/mystuff').onWrite(event => {
return admin.database().ref('/myotherstuff').remove();
});
Firebase Cloud Functions documentation.
【解决方案2】:
exports.myFunction = functions.database.ref('/mystuff')
.onWrite(event => {
admin.database().ref('/myotherstuff').update({//values here});
});
例子:
exports.myFunction = functions.database.ref('/mystuff')
.onWrite(event => {
admin.database().ref('/myotherstuff').update({"username" : "hello, "coins" : 100});
});