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());
})
Related
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
I am trying to retrieve data from my database and my code doesn't return the desired content. It's structure is this:
And this is my code:
firebase.database().ref('proiecte/').once('value').then(function(snapshot){
console.log(snapshot.val().nume)
});
I would expect for my console to return "ROSE" but it returns "undefined". Maybe it helps so I'm mentioning this too: if I run console.log(snapshot.val()) it returns this:
{…}
1544696773350: Object { descriere: "Proiectul este dedicat tinerilor!", nume: "ROSE" }
<prototype>: Object { … }
So, I'm sure that the database is correctly made just that I'm not using the right format for retrieving data. Can anyone tell me where I am wrong please?
To solve this issue, try the following:
firebase.database().ref('proiecte/').once('value').then(function(snapshot){
snapshot.forEach(function(childSnapshot){
let name = childSnapshot.val().nume;
let desc = childSnapshot.val().descriere;
});
});
Here your snapshot is at node proiecte, then you loop using forEach and retrieve the data that's under the random id, so you will be able to retrieve nume and descriere.
I managed to solve this issue!
What I did was to replace ".once('value').then(function(snapshot)" with ".on('child_added', function(snapshot)".
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;
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"}
})
})
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