我正在尝试将我的数据按用户嵌套嵌套有一个项目有一个任务。我似乎无法将其放入钥匙内。
基本上我希望它像-
但是我的结果是-
我的JavaScript
<script>
var database = firebase.database();
var userRef = database.ref('/user');
var projectRef = database.ref('/user/project');
var taskRef = database.ref('/user/project/task');
var userDisplay = userRef.push({
username: 'userA',
firstname: 'John',
lastname: 'Smith'
});
var projectDisplay = projectRef.push({
projectname: 'Project Test 1',
projectdate: '12th December 2019'
});
var taskDisplay = taskRef.push({
taskname: 'Task 1',
taskdate: '12th December 2019',
taskdetail: 'Task Testing'
});
console.log("Running...");
document.getElementById('test').innerHTML= userDisplay + ' ' + projectDisplay + ' ' + taskDisplay;
</script>
答案 0 :(得分:1)
一种解决方案是使用update()
方法,如下所示:
var newUserKey = firebase
.database()
.ref()
.child('user')
.push().key;
var newProjectKey = firebase
.database()
.ref()
.child('user/' + newUserKey)
.push().key;
var newTaskKey = firebase
.database()
.ref()
.child('user/' + newUserKey + '/' + newProjectKey)
.push().key;
var updates = {};
updates['/user/' + newUserKey] = {
username: 'userA',
firstname: 'John',
lastname: 'Smith'
};
var project = {};
project[newProjectKey] = {
projectname: 'Project Test 1',
projectdate: '12th December 2019'
};
updates['/user/' + newUserKey]['project'] = project;
var task = {};
task[newTaskKey] = {
taskname: 'Task 1',
taskdate: '12th December 2019',
taskdetail: 'Task Testing'
};
updates['/user/' + newUserKey]['project'][newProjectKey]['task'] = task;
firebase
.database()
.ref()
.update(updates);