我不确定Java,但对于Web应用程序,您可以使用如下内容:
我想创建一个可重用的函数来添加/保存根节点下的任何对象(即使它在对象内的任何级别都有一个数据数组)。所以我想出了这个。(我不确定是否符合最佳实践,但它工作得非常顺利)
SaveWholeData: function(sKey, oVal, bGenKey) {
bGenKey = bGenKey === undefined ? true: bGenKey;
var oOriginalProperty = angular.copy(oVal);
for (var property in oVal) {
if (oVal.hasOwnProperty(property) && oVal[property] instanceof Array) {
console.log(property);
oVal[property] = "$|$";
}
}
var sOwnRef = SaveDataByKey(sKey, oVal, bGenKey);
for (var property in oVal) {
if (oVal.hasOwnProperty(property) && oVal[property] === "$|$") {
oVal[property] = oOriginalProperty[property];
var updatedReference = sOwnRef + "/" + property;
SaveWholeData(updatedReference, oVal[property], false);
}
}
return true;
},
SaveDataByKey: function(sKey, oVal, bGenKey) {
if (bGenKey) {
var newPostKey = firebase.database().ref(sKey).push().key;
oVal.genKey = newPostKey;
firebase.database().ref(sKey).child(newPostKey).set(oVal);
return sKey + "/" + newPostKey;
}else{
firebase.database().ref(sKey).set(oVal);
return sKey;
}
}
因此,要在 root 下添加新用户,请调用:users
SaveWholeData("users", oUserInfo, true);
并更新现有用户:
SaveWholeData("users"+"/"+ oUserInfo.genKey, oUserInfo, true);