Firebase push -删除唯一对象并插入新对象(基本上覆盖内容)

Firebase push - deletes unique object and inserts new one (Overwrites content basically)

本文关键字:对象 覆盖 基本上 插入 push 删除 唯一 Firebase 新对象      更新时间:2023-09-26

我有一个使用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"
    });
}

当您设置profileArray:

时,您将覆盖整个ref。
...
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,它将更容易快速帮助你。