Firebase snapshot.val()返回[object Object]

时间:2017-07-17 20:59:18

标签: javascript firebase firebase-realtime-database firebase-authentication

我试图从firebase数据库中检索用户但是当我打印snapshot.val()时它会显示[object Object]。如何打印真实数据?谢谢!



  FriendlyChat.prototype.getRandomInterlocutor = async function(){
var numberOfUsers = await this.getNumberOfUsersRef();

var randomIndex = Math.floor(Math.random() * numberOfUsers);
if(randomIndex == 0){
  randomIndex = 1;
}

var ref = await firebase.database().ref('companies/' + this.company + '/users/');
ref.limitToFirst(randomIndex).once('value').then(snapshot =>
{
    var user = snapshot.val();
    console.log('getRandomInterlocutor = ' + user); 
    return user;
});
  }

FriendlyChat.prototype.onAuthStateChanged = function(user) {
  console.log('entro a onAuthStateChanged');
  this.interlocutor = this.getRandomInterlocutor();
  console.log(this.interlocutor);
}




1 个答案:

答案 0 :(得分:1)

只需打印console.log(user);而不是带有obj的字符串。 这再现了它:

var obj = [{a: 1}, {a: 'lucas', b: 2}];
console.log('current obj', obj);

然而,由于用户是一个数组,您可以这样做以获得您想要的每个对象。 (ES6)

user.forEach((u, key) => {
    // u contains your user data object which is like u.uid and u.email or whatever keys you got.
    console.log(key, 'key here contains the strange "firebase array index key"');
    console.log(u);
});