我有一个使用firebase运行的应用程序。当我尝试使用push()方法时,它基本上覆盖了现有的JSON。这是一个例子: 第一次,生成以下JSON:
JSON
"deviceIDs" : {
"-JzCx5C_13eoXPEgklMW" : {
"author" : "gracehop22",
"deviceID" : "99alpha",
"title" : "Announcing COBOL, a New Programming Language"
}
}
下一次,如果我调用相同的函数,将删除上面的JSON并插入一个新的JSON,如下所示:
JSON
"deviceIDs" : {
"-JzCxbuEj2V1kmvvgqnc" : {
"author" : "gracehop22",
"deviceID" : "99alpha",
"title" : "Announcing COBOL, a New Programming Language"
}
}
这是我的代码段:
function CreateUserProfile(UID, name, email, deviceID) {
var ref = new Firebase($scope.firebaseurl + '/' + UID);
var profileArray = {UserProfile:{}};
profileArray.UserProfile.UID = UID;
profileArray.UserProfile.name = name;
profileArray.UserProfile.email = email;
profileArray.UserProfile.deviceID = deviceID;
var onComplete = function (error) {
if (error) {
console.log('Synchronization failed');
} else {
//1. On Success, Store Key User Profile Elements
localStorage.setItem("kasimaProfileInfo",JSON.stringify(profileArray));
$rootScope.username = name;
//2. Hide the feedback and change screens
$timeout(function () {
$scope.HideFeedback();
$scope.ChangeLoc('/featured');
}, 1500);
}
};
ref.set(profileArray, onComplete);
var postsRef = ref.child("deviceIDs");
var newPostRef = postsRef.push();
newPostRef.set({
deviceID: deviceID,
author: "gracehop22",
title: "Announcing COBOL, a New Programming Language"
});
}
答案 0 :(得分:1)
当您设置profileArray
时,您将覆盖整个参考号:
...
ref.set(profileArray, onComplete);
var postsRef = ref.child("deviceIDs");
...
您可能希望在那里使用update()
:
...
ref.update(profileArray, onComplete);
var postsRef = ref.child("deviceIDs");
...
Firebase update()
函数设置传递它的JSON对象中的属性值。因此,您的新profileArray.UserProfile
将替换现有数据。
解决方案是不在本地构建嵌套的JSON结构,而是在需要更新的较低位置更新数据:
ref.child('UserProfile').update(profileArray.UserProfile, onComplete);
这消除了对profileArray
:
var userProfile = {
UID: UID,
name: name,
email: email,
decideID: deviceID
};
ref.child('UserProfile').update(userProfile, onComplete);
有关工作示例,请参阅:http://jsbin.com/ciqoge/edit?js,console
下一次:如果您直接提供这样的jsbin / jsfiddle,快速帮助您将会容易得多。