Iterate nodes to get child key value - javascript

So here is how my test firebase looks
I want to be able to go through the entire list and match the name with a string and if it matches, return the CID. This is what I'm trying from the official documentation but it returns undefined.
fb.on('value', function(snapshot){
var data = snapshot.val();
console.log(data.name);
})
If I log just snapshot.val() then it returns all of them in this format:
{CID: 'XXXXXX' , Name: 'XXXXX'}
Not sure what I'm doing wrong here.

Looks like you should be using data.Name, not data.name

Related

How to get value out of Observable Array nested object

I have searched here for an answer to this question with no luck.
I have an observable array which contains only one entry:
I have it stored in self.user()
POSData.Users.getByEmail(sEmail)
.then(data => {
//console.log(data)
self.user.push(data);
})
Now I simply want to extract a few values and assign them to their own observables, BUT... I can't.
I have tried the following to get the firstName...
console.dir(self.user());
//console.log(self.user()[0].data.firstName());
//console.log(self.user().firstName());
//console.log(self.user().data.firstName());
//console.log(self.user()[0].data.firstName());
//console.log(self.user().data[1].firstName());
Does anyone know how to drill down and get to the information I want?
Thanks for looking.
John
You're storing the raw data you got back from your service into your array. You should access members of that data in that form. The firstName property is not an observable, it's just a string in the data property so you shouldn't be calling it as if it was an observable. The only observable in your example is apparently self.user.
Based on your screenshot your new data looks something like this:
{
data: {
firstName: 'John',
lastName: 'Smith'
},
message: 'User retrieved successfully',
status: null
}
If you want to get the first name of this object in your user array, you'd access it like this:
self.user()[0].data.firstName

Problem with retrieving data from firebase database

I have a problem retrieveing data from firebase database. The data structure is like this:
posts:{
(Random key):{
post:{
text: "random text"
title: "title of some kind"
username: "username"
}
}
}
and the code I tried to retrieve text is:
database.ref("posts").orderByChild("post").on('value', function(snapshot){
console.log(snapshot.val().text);
})
I am new to this firebase thing, so i am sorry if it's a stupid question.
You have to change your code like this:
database.ref("posts").child(randomKey).on('value', function(snapshot){
console.log(snapshot.child("post").child("text").val());
})
Your snapshot is a DataSnapshot and it contains a child() method that is a DataSnapshot itself. To get your text field you just have to use chield("text") and get then the val().
First you can sort the result by using orderBy on any attributes on post.
For example
var sortedpost = firebase.database().ref('posts').orderByChild('post/text');
Or simply you can also use orderByKey to sort based on the document ID.
After this you can get the result you are looking for using on listener as below.
sortedpost.on('value', function(snapshot){
console.log(snapshot.val());
})

Nested orderByChild for Firebase

I am trying to get a list of race times for females in a Firebase database that I have. I may have structured the database incorrectly but I can't see why what I am doing isn't working.
I am trying to get a list of users that are female then check what the fastest time is that matches any of the female uid's. But I am stuck with joining the tables.
My database and code looks like this:
var userref = rootref.child("Users");
var raceref = rootref.child('Races');
userref.orderByChild("Gender").equalTo('Female').on("child_added", function(snapshot) {
console.log(snapshot.key);
raceref.orderByChild("uid").equalTo(snapshot.key).once("child_added", function(raceshot) {
console.log(raceshot.key);
});
});
Then the console only shows the snapshot.key not the raceshot.key:
-864646859
-305907999
If I manually put the numbers from snapshot.key in then raceshot.key does show in the console. I don't get any errors so I am confused as to why I can't use the snapshot.key for the equalTo?
The key of a snapshot is by definition a string, so your in your /Users/$id the $id values are strings. But in the /Races/$raceid/uid property you store the value as a number.
My sense is that the comparison fails on the type. If that is indeed the cause, you should be able to fix it by converting the key to a number:
userref.orderByChild("Gender").equalTo('Female').on("child_added", function(snapshot) {
console.log(snapshot.key);
raceref.orderByChild("uid").equalTo(parseInt(snapshot.key)).once("child_added", function(raceshot) {
console.log(raceshot.key);
});
});

Algolia Instant Search Firebase Cloud Function - how to get the other value?

I don't have much idea about JavaScript, so I used Algolia's Instant Search for Firebase Github Repository to build my own function.
My function:
exports.indexentry = functions.database.ref('/posts/{postid}/text').onWrite(event => {
const index = client.initIndex(ALGOLIA_POSTS_INDEX_NAME);
const firebaseObject = {
text: event.data.val(),
timestamp: event.data.val(),
objectID: event.params.postid
};
In Algolia indices, with timestamp as the key, I get the same value as in text field, but in Firebase backend timestamp is different. How to fix this?
I tried different statements to get timestamp value but couldn't.
Edit
Expected Outcome:
{
text: "random rext",
timestamp: "time stamp string",
author: "author name",
object ID: "object ID"
}
Actual Outcome
{
text: "entered text",
object ID: "object ID"
}
I'm not real clear about your goal. Event has a timestamp property. Have you tried:
const firebaseObject = {
text: event.data.val(),
timestamp: event.timestamp, // <= CHANGED
objectID: event.params.postid
};
If you want a long instead of string, use Date.parse(event.timestamp)
EDIT 2: Answer can be found here.
Original Answer: What Bob Snyder said about the timestamp event is correct.
There may be other fields as well, for example, author_name that we may need to index, is there a generalized way to do that or do I write separate functions for every field?
If you want a general way to add all fields, I think what you are looking for can be found here. This should give you the right guidance to get what you want, i.e save your whole object into the Algolia index.
EDIT:
index.saveObject(firebaseObject, function(err, content) {
if (err) {
throw err;
}
console.log('Firebase object indexed in Algolia', firebaseObject.objectID);
});
event.data.val() returns the entire firebase snapshot. If you want a specific value in your data you add it after .val() for example if every post has an author stored in your firebase database under they key "author" you can get this value using var postAuthor = event.data.val().author
I've included some samples from my code for those interested. A sample post looks like this:
Then inside my cloud functions I can access data like this:
const postToCopy = event.data.val(); // entire post
const table = event.data.val().group;
const category = event.data.val().category;
const region = event.data.val().region;
const postKey = event.data.val().postID;

How to get firebase id

Anyone know how to get the Firebase unique id? I've tried name(), name, key, key(). Nothing works.
I am able to see the data but I have no idea how to get the id back. I need it.
//Create new customers into firebase
function saveCustomer(email) {
firebase.database().ref('/customers').push({
email: email
});
firebase.database().ref('/customers').on("value", function(snapshot) {
console.log(snapshot.val());
console.log(snapshot.value.name());
}, function(errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
The call to push will return a Firebase reference. If you are using the Firebase 3 API, you can obtain the unique key of the pushed data from the reference's key property:
var pushedRef = firebase.database().ref('/customers').push({ email: email });
console.log(pushedRef.key);
The key for the pushed data is generated on the client - using a timestamp and random data - and is available immediately.
Calling push() will return a reference to the new data path, which you can use to get the value of its ID or set data to it.
The following code will result in the same data as the above example, but now we'll have access to the unique push ID that was generated:
// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();
// Get the unique ID generated by push()
var postID = newPostRef.key();
Documentation.
but this method won't work when you also need the id beforehand
for example to save it in the database itself.
Firebase suggests this:
// Add a new document with a generated id.
var newCityRef = db.collection("cities").doc();
--for some reason, push() and key() didn't work for me. also in this case the reference contains the whole path. so need a different method for getting the id.
Doing this below helped to get the id from the reference and use it.
const ref = db.collection('projects').doc()
console.log(ref.id) // prints the unique id
ref.set({id: ref.id}) // sets the contents of the doc using the id
.then(() => { // fetch the doc again and show its data
ref.get().then(doc => {
console.log(doc.data()) // prints {id: "the unique id"}
})
})

Categories

Resources