Reputation: 1721
I have an query and it returns snapshot;
ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {})
When I print snapshot with ;
console.log(snapshot.val());
it is printed as follows;
{'-LBHEpgffPTQnxWIT4DI':
{
date: '16.05.2018',
first: 'let me in',
index: 1,
second: 'let others in'
}
},
I need to take the value date, first value of this snapshot.
I tried;
childSnapshot.val()["first"]
childSnapshot.val()["date"]
or
childSnapshot.child.('first')
childSnapshot.child.('date')
but there is no success.
Please indicate me the mistake I am doing...
My full code is as below;
var indexRef = db.ref("/LastIndex/");
var ref = db.ref("/Source/")
indexRef.on("value", function(indexSnapshot) {
console.log(indexSnapshot.val());
var currentIndex = indexSnapshot.val()
ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {
console.log(snapshot.val());
if(snapshot !== null) {
snapshot.forEach(function (childSnapshot) {
if(childSnapshot !== null) {
var newRef = db.ref("/ListTest/");
var key = newRef.push({
"firstLanguageWord": childSnapshot.val()["first"] ,
"secondLanguageWord": childSnapshot.val()["second"] ,
"wordType": childSnapshot.val()["type"],
"date": childSnapshot.val()["date"],
"translateType": childSnapshot.val()["transType"]
});
currentIndex++;
indexRef.set(currentIndex);
}
});
}
});
BR,
Erdem
Upvotes: 0
Views: 200
Reputation: 83058
Update, following your comments below and the update to the original question:
If it appears that your code is "iterating infinitely" it is because you use the on() method with your first query. As a matter of facts, the on()
method "listens for data changes at a particular location.", as explained here.
If you just want to query once the reference, use the once()
method instead. The doc is here.
The following is a Query, because you call the orderByChild()
method on a Reference (as well as an equalTo()
method).
ref.orderByChild("index").equalTo(currentIndex)
As explained here in the doc:
Even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you need to loop over the result:
ref.once('value', function(snapshot) { snapshot.forEach(function(childSnapshot) { var childKey = childSnapshot.key; var childData = childSnapshot.val(); // ... }); });
So you should do:
ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
console.log(childSnapshot.val().first);
console.log(childSnapshot.val().date);
});
});
Upvotes: 1