【问题标题】:How to verify if data exist in Firebase如何验证 Firebase 中是否存在数据
【发布时间】:2016-12-06 11:35:07
【问题描述】:

我在将数据保存到 firebase 时遇到问题,因为我的数据只更新数据库中已有的数据,它不会插入新数据。那是当我创建一个新用户并尝试在 Firebase 中获取此数据时解决了一个练习,它返回了此错误。

FIREBASE 警告:用户回调引发了异常。 TypeError: 无法将 undefined 或 null 转换为对象。

function writeUserData(userId, data) {
    var key    = Object.keys(data)[0];
    var values = Object.values(data)[0];
    console.log(values);

    firebase.database().ref('users/' + userId + '/' + jsData.topicId + '/' + key).set({
            topic_log: values
        });
    }

【问题讨论】:

    标签: javascript json firebase


    【解决方案1】:

    在此处查看此代码:

    function go() {
       var userId = prompt('Username?', 'Guest');
       checkIfUserExists(userId);
    }
    
    var USERS_LOCATION = 'https://SampleChat.firebaseIO-demo.com/users';
    
    function userExistsCallback(userId, exists) {
      if (exists) {
        alert('user ' + userId + ' exists!');
      } else {
        alert('user ' + userId + ' does not exist!');
      }
    }
    
    // Tests to see if /users/<userId> has any data. 
    function checkIfUserExists(userId) {
      var usersRef = new Firebase(USERS_LOCATION);
      usersRef.child(userId).once('value', function(snapshot) {
        var exists = (snapshot.val() !== null);
        userExistsCallback(userId, exists);
      });
    }
    

    【讨论】:

    • 谢谢,您的评论对我帮助很大
    【解决方案2】:

    您可以使用数据快照的exists()方法来检查数据。

    例如:

    var userRef = firebase.database().ref('users/' + userId);
    userRef.once('value', function(snapshot) {
        if (snapshot.exists){
            console.log('user exists');
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 2012-08-14
      • 2015-11-29
      • 1970-01-01
      • 2023-01-23
      • 2018-07-08
      相关资源
      最近更新 更多