2017-02-24 43 views
0

存在我想,如果它存在更新数据火力

var ref = firebase.database().ref().child('users'); 
var refUserId = firebase.database().ref().child('users').orderByChild('id').equalTo(Auth.$getAuth().uid); 
refUserId.once('value', function (snapshot) { 
     console.log(snapshot); 
     if (snapshot.exists()) { 
      snapshot.ref().update(vm.user_infos); 
     } else { 
     ref.push({ 
      player: vm.user_infos.player, 
      id: vm.user_infos.id 
     }, function(error) { 
     console.log(error); 
    }) 
    } 
}); 

推工作正常更新数据,但更新没有。

snapshot.ref不是一个函数

在快照()日志控制台:

enter image description here

我想这样太:

if (snapshot.exists()) { 
    refUserId.update({ 
     player: vm.user_infos.player, 
     id: vm.user_infos.id 
    }, function(error) { 
    console.log(error); 
}) 

结果:

refUserId.update不是函数

用户结构

enter image description here

回答

1

第一个问题是,该快照的ref property是一个对象 - 不是一个函数。

第二是快照指users路径,所以你应该检查是否有符合您查询这样的用户:

var ref = firebase.database().ref().child('users'); 
var refUserId = ref.orderByChild('id').equalTo(Auth.$getAuth().uid); 
refUserId.once('value', function (snapshot) { 
    if (snapshot.hasChildren()) { 
    snapshot.forEach(function (child) { 
     child.ref.update(vm.user_infos); 
    }); 
    } else { 
    snapshot.ref.push({ 
     player: vm.user_infos.player, 
     id: vm.user_infos.id 
    }); 
    } 
}); 

如果你想知道什么时候updatepush已完成,你可以使用承诺:

refUserId 
    .once('value') 
    .then(function (snapshot) { 
    if (snapshot.hasChildren()) { 
     return snapshot.forEach(function (child) { 
     child.ref.update(vm.user_infos); 
     }); 
    } else { 
     return snapshot.ref.push({ 
     player: vm.user_infos.player, 
     id: vm.user_infos.id 
     }); 
    } 
    }) 
    .then(function() { 
    console.log('update/push done'); 
    }) 
    .catch(function (error) { 
    console.log(error); 
    }); 
+0

谢谢。但更新后,而不是更新信息,它创建了一个新的 http://imgur.com/a/kDNwY –

+0

我已经更新了答案。 – cartant

+0

谢谢。我只是在你的代码中修改它:child.ref()。update(vm.user_infos);为此:child.ref.update(vm.user_infos); 工作得很好 –