我有一个使用 firebase 运行的应用程序。当我尝试使用 Push() 方法时,它基本上会覆盖现有的 JSON。这是一个例子: 第一次,生成以下 JSON:
<小时/>JSON
“设备ID”:{
“-JzCx5C_13eoXPEgklMW”:{
“作者”:“gracehop22”,
“设备ID”:“99alpha”,
"title": "宣布 COBOL,一种新的编程语言"
}
}
下次,如果我调用相同的函数,上面的 JSON 会被删除,并插入一个新的 JSON,如下所示:
<小时/>JSON
“设备ID”:{
“-JzCxbuEj2V1kmvvgqnc”:{
“作者”:“gracehop22”,
“设备ID”:“99alpha”,
"title": "宣布 COBOL,一种新的编程语言"
}
}
这是我的代码片段:
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"
});
}
<小时/>
最佳答案
设置 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,那么快速帮助您会更容易。
关于javascript - Firebase 推送 - 删除唯一对象并插入新对象(基本上覆盖内容),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32574942/