Firebase数据库更新数据会删除旧子项

时间:2017-05-15 08:44:59

标签: android firebase firebase-realtime-database

我想在firebase数据库中添加嵌套子项。 我的json的结构是

{
    "Users": {

    "user1": {
        "courses": {
            "science": {
                "maxMarks": 100,
                "teacher": "Andrew",
                "title": "Amazing Science",
                "status": "cleared"

            },
            "maths": {
                "maxMarks": 100,
                "teacher": "Simon",
                "title": "Elementary Mathematics",
                "status": "cleared"
            },
            "history": {
                "maxMarks": 80,
                "teacher": "Sarah",
                "title": "History",
                "status": "cleared"
            }
        }

    }
}

}

一旦我添加一个新课程,它就会覆盖我的整个课程,而不是在里面添加一个新孩子。

我也尝试过updateChildren但没有成功.. 请帮忙。

FirebaseDatabase mDatabase = FirebaseDatabase.getInstance().getReference("Users");


DatabaseReference newPostRef = mDatabase.child("user1").child("courses").child("Calculus").push();

                            Map<String, Object> newPost = new HashMap<String, Object>();
                            newPost.put("title", "Calculus");
                            newPost.put("teacher", "Mishal");
newPost.put("maxMarks", 100);
newPost.put("status", "cleared");
                            newPostRef.setValue(newPost);

1 个答案:

答案 0 :(得分:2)

我建议您使用push()方法生成的唯一ID来代替课程名称。这意味着您的数据库结构可能如下所示:

"user1": {
    "courses": {
        "-Kdfqjidfiqifnqifn": {
            "courseName": "science",
            "maxMarks": 100,
            "teacher": "Andrew",
            "title": "Amazing Science",
            "status": "cleared"

        },
        "-Kdfqjidfwefwty34d": {
            "courseName": "maths",
            "maxMarks": 100,
            "teacher": "Simon",
            "title": "Elementary Mathematics",
            "status": "cleared"
        },
        "-Kdfqjidfwer3t4yhdg": {
            "courseName": "history",
            "maxMarks": 80,
            "teacher": "Sarah",
            "title": "History",
            "status": "cleared"
        }
    }

}

您需要直接在引用中使用此方法,如下所示:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("User").child(userId).child("courses");
DatabaseReference keyReference = databaseReference.push();
keyReference.setValue(yourMap)

其中userId是用户的id

通过这种方式,您不会更新现有数据,您将添加新数据。

希望它有所帮助。