【问题标题】: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');
}
});