Firebase在特定推送ID

时间:2017-07-12 07:12:28

标签: javascript firebase react-native firebase-realtime-database

我正在努力实现这一目标:

households {
    householdID1 : {
        address : "BLK 16, Woodlands Street"
        accounts : {
            accountID1 : true,
            accountID2 : true,
        }
    }
}

但是当我试图插入时,它就像这样:

enter image description here

这是我的代码:

 var householdRef = firebase.database().ref('households');

var householdData = {
    address : "Blk 164"
}

householdRef.push(householdData);
var householdKey = householdRef.key;
console.log(householdKey);

var query = firebase.database().ref('accounts').orderByChild('email').equalTo('gab@gmail.com');
query.once( 'value', data => {
    data.forEach(userSnapshot => {
        let userKey = userSnapshot.key;
        console.log('userKey ' + userKey);

        firebase.database().ref('households').child(householdKey).child('accounts').push().set({
          userKey : true,
        }), (error) => {
          if (error) {
            console.log(error.message);
          }else{
            // Success
          }
        }
    });
});

在我获得了HouseholdKey之后,我试图在该特定的家庭关键孩子下添加新的嵌套孩子。我首先循环通过帐户记录找到帐户的唯一ID,然后我继续添加。但最终变得像上面这张照片。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

如果您使用push()功能,firebase会为该子项生成一个新密钥。

我无法调试,但我认为这是解决方案:

var householdRef = firebase.database().ref('households');

var householdData = {
  address : "Blk 164",
};

householdRef.push(householdData);
var householdKey = householdRef.key;

var query = firebase.database().ref('accounts').orderByChild('email').equalTo('gab@gmail.com');
query.once( 'value', data => {
    data.forEach(userSnapshot => {
        let userKey = userSnapshot.key;

        firebase.database().ref('households').child(householdKey).child('accounts').update({
          [userKey] : true,
        }), (error) => {
          if (error) {
            console.log(error.message);
          }else{
            // Success
          }
        }
    });
});