I tried to retrieve data from firebase database. The returned data shows like
undefined undefined undefined
the code I used is
var query = firebase.database().ref().child("users/-Ly-dBv9xSiBf-UO0A8Q").orderByKey();
query.once("value") .then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val().messageText;
document.writeln(childData);
});
});
It shows undefined because first, the reference is at the random ID node therefore you don't have to loop. Second, you don't have an attribute called messageText in your database. Your code should be like this:
var query = firebase.database().ref().child("users/-Ly-dBv9xSiBf-UO0A8Q").orderByKey();
query.once("value") .then(function(snapshot) {
var childData = snapshot.val().password;
var userId = snapshot.val().user_id;
document.writeln(childData);
});
Related
I have the following database:
I want to retrieve the value of name given a specific ID value in JavaScript.
Right now I have the following code, but it doesnt seem to acces both ID and name nodes:
var user = db.ref("Users").orderByChild("ID").equalTo("12345");
users.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
...
This can be achieved with the code below:
var ref = db.ref("Users").orderByChild("ID/value").equalTo("12345");
ref.on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
var name = childData.name.value;
});
});
Is it possible to implement a calendar on my website which shows user submissions by their date on a calendar?
The following code captures some test variables and I would like them shown in the calendar by the date they were submitted.
function startDatabaseQueries() {
alert("StartQueries");
// Get current user info
var myUserId = firebase.auth().currentUser.uid;
var username = firebase.auth().currentUser.displayName;
// Get posts
alert("1");
var testRef = firebase.database().ref('posts').orderByKey();
testRef.once('value', function(snapshot) {
var results = [];
snapshot.forEach(function(childSnapshot) {
//var key = childSnapshot.key;
var childData = childSnapshot.val();
// console.log(childData);
var author = childSnapshot.val().author;
console.log(childSnapshot);
document.getElementById("demo").innerHTML = author;
});
});
}
The
console.log(childSnapshot)
shows the following code in the console: (Variable results omitted)
Author:
AuthorPic:
submitted:
title:
uid:
I would recommend grabbing the date as well and store it on the database with the format "yyyyMMdd". Then, when you want to read the data, you would simply use:
var testRef = firebase.database().ref('posts').orderByChild("dateAdded");
So I am doing a query to bring back a list of records, these records have a link to the user that created the record. The link is to the object.
My query gets me the object but I cant then access the fields of that object (except of course ID)
query.equalTo("search", search);
query.include("user");
query.find({
success: function(Report) {
for (var i = 0; i < Report.length; i++) {
var test = Report[i].id;
query.get(test, {
success: function(result) {
var reportDescription = result.get("reportDescription");
var reportPicture = result.get("reportPicture");
var reportPosition = result.get("reportPosition");
var reportType = result.get("reportType");
var reportDate = result.get("createdAt").toLocaleString();
var reportSearchId = result.get("search").id;
var user = result.get("user")
console.log(user)
var reportSearchBy = user.username;
},
error: function(result, error) {
alert(error.message);
}
});
};
},
error: function(error) {
alert(error.message);
}
});
What am I doing wrong?
i tried to run similar code to what you did. when i tried to access with dot notation i get undefined but when i tried to get it with .get("fieldName") it works..
here is my code:
var FileTest = Parse.Object.extend("FileTest");
var query = new Parse.Query(FileTest);
query.include("user");
query.find().then(function(results){
var lastItem = results[results.length - 1];
if (lastItem){
var user = lastItem.get("user");
console.log(user.get("username"));
}
},function(error){
});
please notice that i also use Promise for better coding and in order to get the username i did lastItem.get("username")
so please try to replace user.username with user.get("username")
and see if it works.
I am trying to retrieve data from a Users node in Firebase and use the retrieved data in a set() to another node. Specifically I want to use my user UID to look at which "branch" the user belongs to and then use the value in the set()
I have the following snapshot to get the "branch" of the user. It logs to the console the correct value
var ref = new Firebase("firebase/url");
var authData = ref.getAuth();
var userUID = authData.uid
var userRef = new Firebase("firebase/URL" + userUID);
userRef.once("value", userBranch)
function userBranch(snapshot) {
var data = snapshot.val();
console.log(data.branch);
};
With the returned "branch" value I want to use it in the following set()
var postsRef = ref.child("Posts");
var newPostRef = postsRef.push();
var postID = newPostRef.key();
postsRef.child(postID).set({
branch: data.branch})
What is the best way to take the value out of the function userBranch so I can use it in my set()?
You are using .once a little bit wrong, but you have the right idea.
var ref = new Firebase("firebase/url");
var authData = ref.getAuth();
var userUID = authData.uid
var userRef = new Firebase("firebase/URL" + userUID);
// Second parameter is callback function that receives data (snapshot)
userRef.once("value", function(snapshot) {)
var data = snapshot.val();
console.log(data.branch);
// Save value at data.branch
var dataBranch = data.branch;
var postsRef = ref.child("Posts");
var newPostRef = postsRef.push();
var postID = newPostRef.key();
// Save it, erasing all previous data at location
postsRef.child(postID).set({
"branch": dataBranch
});
};
You were a little mixed up with the second parameter for .once.
References:
Firebase | .push
Firebase | .once
Firebase | .set
var url = "http://api.reddit.com/";
var dataArray = [];
var working = function(){
var getData = JSON.parse(this.responseText);
var titles = getData.data.children;
for(var i=0, j=titles.length; i<j; i++)
{
var title = titles[i].data.title;
dataArray.push({
title: title,
favorite: 0
});
}
save(dataArray);
}; //working
var save = function(arg){
console.log(arg);
var db = Ti.Database.open("newData");
db.execute('CREATE TABLE IF NOT EXISTS redditTitles (id INTEGER PRIMARY KEY, name TEXT, favorite INTEGER)');
db.execute('INSERT INTO redditTitles (name, favorite) VALUES (?, ?)', arg.title, arg.favorite);
var rowID = db.lastInsertRowId;
//newRow.id = rowID;
//rows.close();
db.close();
gather();
};
var dataContent = [];
var gather = function(){
var db = Ti.Database.open("newData");
var dbRows = db.execute("SELECT name, favorite FROM redditTitles"); // Returns a Result Set object
while(dbRows.isValidRow()){
dataContent.push({
title: dbRows.fieldByName("name"),
fav: dbRows.fieldByName("favorite")
});
console.log("dataContent: "+ dataContent.title);
dbRows.next();
}
dbRows.close();
db.close();
console.log(dataContent);
userInterAPI();
};
var error = function(){
alert("Please check your network connection and try again.");
};
var client = Ti.Network.createHTTPClient({
onload: working,
onerror: error,
timeout: 5000
});
client.open("GET", url);
client.send();
So Basically me and my instructor have been scratching our heads trying to figure out why the arg will show all of the data but after the data is saved and we go to re console log it out, it will show up as null. Not sure why. Someone please help me!
You are saving just one item (Incorrectly - that's why is undefined). If you want to save everything you have to iterate through whole array.
var save = function(arg) {
console.log(arg);
var db = Ti.Database.open("newData");
db.execute('CREATE TABLE IF NOT EXISTS redditTitles (id INTEGER PRIMARY KEY, name TEXT, favorite INTEGER)');
db.execute("BEGIN"); // Transaction
arg.forEach(function(item) {
db.execute('INSERT INTO redditTitles (name, favorite) VALUES (?, ?)', item.title, item.favorite);
//var rowID = db.lastInsertRowId;
});
db.execute("COMMIT");
db.close();
gather();
};
In the function called gather - if you want to see selected title you should use:
console.log(dbRows.fieldByName("name"))
alternatively (This is what you wanted to use):
console.log(dataContent[dataContent.length - 1].title)
instead of
console.log(dataContent.title); // dataContent is an Array.
*Of course you better avoid using dataContent.length in every iteration. That's just an example.