firebase nested objects returning null - javascript - javascript

I want to get the nested child objects like in the images but it is returning null. I want values of price and quantity and show them in table.
Check this database image
here.
Code
var countRef = firebase.database().ref('Orders/' + listid);
countRef.on('value', snapshot => {
var b = snapshot.child("price").val();
var c = snapshot.child("quantity").val();
console.log(c);
});

You are pointing to the wrong path that's why you are getting null. Here is what the Firebase docs say:
If there is no data, the snapshot returned is null.
I can't see your entire database structure from the image but try to double check the path and here is my best guess:
var foodItems = firebase.database().ref(`Orders/'${listid}/foodItems`)
foodItems.on('value', snapshot => {
// the snapshot should return the foodItems array
snapshot.forEach((obj) => {
console.log(obj.price)
console.log(obj.quantity)
})
})

If your listid is and exist key, then you mistyped the path: fooditems so try this;
var countRef = firebase.database().ref('Orders/' + listid);
countRef.on('value', snapshot => {
if (snapshot.exists()) {
var b = snapshot.child("fooditems/price").val();
var c = snapshot.child("fooditems/quantity").val();
console.log(c);
}
});

Related

Get Firebase child value in JavaScript

I want to only get a specific child value from Firebase using JavaScript.
I always get the entire child values.
This is what it looks like:
Child a -
|- fcmToken: 'abcdefg'
Child a -
|- fcmToken: 'hijklmn'
I always get the entire thing. "Child a – fcmToken: 'abcdefg'"
But I only want to get the fcmToken value 'abcdefg' and 'hijklmn'
Ho can I do so?
I tried this:
return admin.database().ref('/fcmToken').once('value', snapshot => {
var uid = snapshot.val();
return admin.database().ref('/fcmToken/' + uid).once('value', snapshot => {
var fcmToken = snapshot.val();
console.log('FCMTOKEN:', fcmToken)
});
But it's not working. Any ideas, how I can only get the desired values 'abcdefg' and 'hijklmn'
After days of trying I have finally found a solution!
Here is what I did:
return admin.database().ref('/fcmToken').once('child_added', snapshot => {
var uid = snapshot.key;
return admin.database().ref('/fcmToken/' + uid + '/fcmToken').once('value', snapshot => {
var fcmToken = snapshot.val();
});
The var fcmToken = snapshot.val(); was the data, I needed and was trying to get.

Update an Object in indexed db by ignoring a value

I have written the below code
updatePublication(projectName, publicationId, publicationObj, callback) {
let self = this;
this.initDatabase(function (db) {
let tx = self.db.transaction(self.PUBLICATIONS, self.READ_WRITE);
let store = tx.objectStore(self.PUBLICATIONS);
let index = store.index(self.PROJECT_NAME);
let request3 = index.openCursor(IDBKeyRange.only(projectName));
console.log("hrere");
request3.onsuccess = function () {
let cursor = request3.result;
if (cursor) {
let updateObject = cursor.value;
if (updateObject.publicationID == publicationId) {
updateObject.publicationObject = publicationObj;
cursor.update(updateObject);
callback(publicationId);
}
cursor.continue();
} else {
callback(publicationId);
}
};
});
}
But this give error:
I checked the cause of error. It is beacuse , publicationObj which is passed has an object named _requestObjectBuilder which is of the type Subscriber.
used somewhere in the code like this:
_requestObjectBuilder = interval(1000).pipe(tap(() => {}));
Is there any way i can modify my updatePublication code to ignore this value?
Does indexed db support a query for ignoring a value and saving the data?
Note: If i set publicationObj._requestObjectBuilder = undefined, the data gets saved to indexedDB. But this breaks the functionality where _requestObjectBuilder is used.
Fixed the issue by cloning the object and setting it to undefined
let clonedObject = Object.assign({}, publicationObject);
clonedObject._requestObjectBuilder = undefined;
Now i am updating the clonedObject

Sort list of Objects react-native by value not key

I have problems to sort a list of objects in React-native by a time value. I can't find the answer online. Do you have any suggestions?
My console log in chrome of original object:
Firebase database structure
JSON.stringify(myObject) output:
myObject={"-LAqmXKSdVVH6wirFa-g":
{"desc":"fdf","price":"rrrr","receiveHelp":true,"subject":"Single Variable
Calculus","time":1524558865757,"title":"Test1"},"-LAqmZlBFGoygfTsGQ0e":
{"desc":"dsfdsfd3","price":"333","receiveHelp":true,"subject":"Single
Variable Calculus","time":1524558875724,"title":"Test2"},"-
LAqmcipUjlwLWTrRCw4":
{"desc":"werwerwe55","price":"44","receiveHelp":true,"subject":"Single
Variable Calculus","time":1524558891956,"title":"Test3"},"-
LArMeYfHG6QMg_Frn9A":
{"desc":"3","price":"3","receiveHelp":true,"subject":"Single Variable
Calculus","time":1524568598762,"title":"Annons 1"},"-LArMjg5MkF5cMPZd_Fz":
{"desc":"2222","price":"2","receiveHelp":true,"subject":"Single Variable
Calculus","time":1524568619782,"title":"Annons2"},"-LArNM-3Ij60XmSOBwvr":
{"desc":"22","price":"","receiveHelp":true,"subject":"Single Variable
Calculus","time":1524568780803,"title":"Hej1"},"-LArNPugIfX1pPVZJ11e":
{"desc":"f","price":"2","receiveHelp":true,"subject":"Single Variable
Calculus","time":1524568796844,"title":"Hej2f"}}
What I have tried so far:
firebase.database().ref('/users').once('value').then((snapshot) => {
const ads = snapshot.val();
let myObject = {};
Object.keys(ads).map((objectKey) => {
const value = ads[objectKey];
myObject = Object.assign(value.ads, myObject);
});
//Here i want to sort myObject by time and get the latest first
console.log(myObject)
You first need to combine ads or all users into one array and then sort
let sortedAdds = Object.keys(usersData)
.reduce((prev, userId) => {
let ads = usersData[userId].ads;
ads = Object.keys(ads).map(key => {
return { ...ads[key], id: key };
});
return prev.concat(ads);
}, [])
.sort((a, b) => (a.time - b.time));
([obj1, obj2]).sort((tm1, tm2) => {
if (tm1.time > tm2.time) {
return 1;
}
if (tm1.time < tm2.time) {
return -1;
}
return 0;
})
You could, instead of sorting in your front-end, use the sorting capabilities of the Firebase database by doing:
var ref = database.ref('users/' + adId + '/ads').orderByChild('time');
If you then loop over the results of this query, the ads will be ordered according to the time
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
console.log(childData);
});
});
Edit: if you want to have the "latest gets first" which I understand as "the most recent should be the first", you should then store the time*(-1) instead of time (time being the milliseconds since the unix epoch, as show in your question)

javascript cannot access array methods on push

I have a react app that pulls data from firebase. It adds data to the array fine. But cannot be accessed. calling the index returns undefined and length of array is 0. but when you print the array the console shows there is an element inside. Whats going on?
componentWillMount() {
itemsRef.on('value', (snapshot) => {
let items = snapshot.val();
let keys = Object.keys(items);
for(var i = 0; i < keys.length; i += 1) {
let k = keys[i];
let name = items[k].name;
let start = items[k].start;
this.state.timers.push( {
name: name,
start: start
} );
}
});
console.log(this.state.timers); // shows an array with stuff in it
this.setState({timers: this.state.timers}); // timers dont get added
// you cant even access elements in the array.
// ex: this.state.timers[0] returns undefined, but the console shows that it exists when the whole array is printed.
}
You shouldn't mutate directly your state like you do in the `this.state.timers.push({})``
You should do something like that:
itemsRef.on('value', (snapshot) => {
const items = snapshot.val();
this.setState({
timers: [
...this.state.timers,
...Object
.keys(items)
.map(key => {
const { name, start } = items[key];
return { name, start };
}),
],
});
});
You shouldn't push directly to the state. Instead you should to something like this:
ES6 variant
const timers = [...this.state.timers];
timers.push({ name, start });
this.setState({ timers })

How to get only one element from an array (firebase database, nodejs)

If I use limitToLast(1), then I still get an object, with one key-value pair. To get the value, I use this code:
db.ref('/myarray').limitToLast(1).once('value').then(function(snapshot) {
var result = snapshot.val();
var lastElem;
var lastKey;
for(var i in result) {
lastElem= result[i];
lastKey = i;
break;
}
...
});
It works, but I think I do it wrong. But haven't found any better solution in the docs. How should I load only one element?
The database looks like this:
When using Firebase queries to get children, use the "child_added" event:
db.ref("/myarray")
.orderByKey() // order by chlidren's keys
.limitToLast(1) // only get the last child
.once("child_added", function(snapshot) {
var key = snapshot.key;
var val = snapshot.val();
...
});

Categories

Resources