如果您查看Firebase实时数据库映像,首先会更容易:
因此,在我的代码中,我创建了一些带有id的“实用”(在这种情况下为152648 ......)然后,在该对象中创建了一个“grupos”(组)列表。问题来了,为此,我使用.push(),因此Firebase在firebase主节点内创建一个列表,但问题是它使用的'key'是随机的,所以,我想访问最后一个步骤称为“alumnos”,但由于我不知道以前的密钥我无法访问那里。我尝试使用ID来推送对象,但它会添加ID,然后是密钥。
我的代码:
//don't take care about what is values[], grupoList[] and so on
//I just take values from a checkbox on the HTML and I send them to the 'grupo' value of the object 'practica'
addGroup(){
let y=0;
for(let i=0; i<this.values.length; i++){
if(this.values[i] == true){
this.grupoList[y] = this.profiles[i];
y++;
}
}
this.grupo.alumnos = this.grupoList;
this.practica.grupo = this.grupo;
this.practicaService.anyadirGrupos(this.practica);
this.navCtrl.setRoot(VerGruposPage, {'data': this.practica});
}
PracticaService:
//Here is where I work with firebase adding the 'grupo'
public anyadirGrupos(practica){
this.afDB.database.ref('practicas/' + practica.id + '/grupos/').push(practica.grupo);
}
//to access the node 'alumnos' (it doesn't work)
public getAlumnos(practica){
return this.afDB.list('practicas/' + practica.id +'/grupos/' + '../alumnos/')
}
任何想法在不知道前一步的情况下访问最后一步?
答案 0 :(得分:0)
您可以有两种不同的方法:
1 /在没有额外密钥的情况下写下“sub-grupos”
这意味着拥有这样的数据库结构:
- practicas
-idPracticas
-grupos
-alumnos
-0 ....
-1 ......
-anotherGroupName
-0 ....
-1 ......
为此,您应该使用set()
代替push()
2 /保持结构并循环遍历不同的子节点
db.ref('practicas/' + practica.id + '/grupos/').orderByKey().once('value').then(function(snapshot) {
console.log(snapshot.val());
snapshot.forEach(function(childSnapshot) {
console.log(childSnapshot.val());
console.log(childSnapshot.val().alumnos[0]);
console.log(childSnapshot.val().alumnos[1]);
});
});