Im using the following loop to get data from a table which is working fine:
database.once("value", function(snapshot){
snapshot.forEach(snap => {
log.console(snap.val().about_me)
})
Its displaying the data to logs as expected, But i can't seem to get the object id?
I need to get the value 49GRZb8B31MUfpBN3zvHKOHCMOa2
I have tried:
snap.val().key;
This returns undefined
And have tried snap.val()[0];
which returns me everything in the object
snap is a DataSnapshot type object. You can see that it has a property called key. So, you need to reference that property directly on the DataSnapshot like this:
snap.key // correct
But not via the raw data object like this:
snap.val().key // incorrect, you have no child named 'key' in your data
Related
I have this json in my server:
{"user":"bla","password":"passbla"}
and in side my ts file I accessing it like that:
this.http.get('http://myserver.com/myjson.json').subscribe(data => {
alert(data.text()); });
I getting the json text in the alert box all OK.
But I need to access a certain element in this json(let's say the "user" element)
but this :
alert(data.user);
or
alert(data.json().user);
are all returning undefined if any...
How do I get a certain element value inside a json like this?
alert(data.json()[0].user)
is the way to access the element...
Here is the code for when I'm pushing the data to Firebase:
firebase.database().ref(`booklogs/${uid}/${book_id}`).push(page_id)
booklogs :
{HUMjSHxVKAPfVXzOId9zCBkGOgv1:{
book28917: {
-KYp4FdYYODDZG1FX-Pb: 1
}
}
}
My problem is when I query the data, the child node of the ${book_id} includes the push key, but I only want to get the value which is 1 and not the push key.
The code I use to query is:
var booklogs = db.ref(`booklogs/${uid}/${project}`);
booklogs.once('value')
.then((snapshot) => {
console.log(`pages viewed are ${snapshot.key}: ${snapshot.val()}`);
console.dir(snapshot.val());
}).catch((error) => {
console.log(`Error : ${error}`);
});
The data returned in the console is:
pages viewed are 2634651: [object Object]
{ '-KYp4FdYYODDZG1FX-Pb': 1 }
Any input would be much appreciated. Thanks!
If you only want the '1' and not the push key, try using .set()
firebase.database().ref(`booklogs/${uid}/${book_id}`).set(page_id)
That will get rid of the object and just give you the value that you wanted. Push automatically generates a key for every value you add, so you will always get an object back. From the Firebase docs - "For basic write operations, you can use set() to save data to a specified reference, replacing any existing data at that path."
https://firebase.google.com/docs/database/web/read-and-write
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"}
})
})
I am trying to display dynamic content by using the mandrill template api in a node project.
I have followed the docs and looked at plenty of examples, and for the most part can get things working.
However, when I try to access properties of an object that I pass through the api in the mandrill template, it does not display anything.
Here is my mandrill template (using handlebars):
<p>{{greeting}} {{person.firstName}},</p>
<p>{{greeting}} {{person.0.firstName}},</p>
<p>Your location is {{person.location}}.</p>
Now, the greeting does display the value passed in the global_merge_vars part. But the properties for the person object do not get displayed, as if they are undefined.
Here is part of the json being sent:
var greeting = "Hello ";
var person = {firstName:"testfname",location:"testlocation"};
var globalMergeVars = [
{"name": "greeting","content":greeting},
{"name": "person","content": person},
];
Am I not passing the object correctly or naming the 'name' property correctly in the api call? I have tried a bunch of different things. I know that I could create multiple vars inside the globalMergeVars object instead of passing the entire person object, however I have a lot more properties attached to the person object.
I have also successfully used an each loop for an array of items and that all gets displayed correctly.
Thanks.
In the following JSON how to access id and name
console.log($scope.mylist)
{"data":"{\"projects\":[{\"id\":\"3\",\"title\":\"MYCLOUD\",\"desc\":\"DESC\"}]}"}
I tried the following
console.log($scope.mylist.data) //undefined
console.log($scope.mylist["data"])//undefined
console.log($scope.mylist.projects)//undefined
console.log($scope.mylist["projects"]) //undefined
Your data property contains JSON, so you need to JSON.parse that too.
$scope.mylist.data.projects = JSON.parse($scope.mylist.data);
Then you should be able to access it with
$scope.mylist.data.projects[0].id //etc
Though there's an underlying problem of how you're getting/sending that JSON.