Get Firebase child value in JavaScript - 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.

Related

How to get random pushed key from firebase realtime database

i am about to delete the child -MAkugTU_85UTvn4g9Hn by date(timestamp) and videoId value in folowing image
i tried below code only return the parent called oUi3NI9SdcbCC6v5EmygDNV4lrg1 not the random pushed key, any suggestion will be appreciated. thanks
const uid = firebase.auth().currentUser.uid;
const ref = firebase.database().ref('posts').child(uid);
ref.orderByChild('date').equalTo(date).once("value",snapshot => {
console.log(snapshot.key) // oUi3NI9SdcbCC6v5EmygDNV4lrg1
});
const ref = firebase.database().ref('posts').child(uid);
ref.orderByChild('date').equalTo(date).once("value",snapshot => {
console.log(snapshot.key) // key of parent
snapshot.forEach((childSnapshot) => {
console.log(childSnapshot.key) //here you will get key of each child
}
});
Then by using child key you can do whatever you want to do with it.

Retrieving the first element from data snapshot

I'm trying to pull out the first record from the code below.
exports.sendBuyerNotification = functions.database.ref('/Bids/{uid}').onWrite((async(change,context)=>{
const bid= change.after.val();
const prodid = bid.prodID;
const new_price = bid.price;
const biddata= admin.database().ref('/Bids');
biddata.orderByChild('prodID').equalTo(prodid).limitToLast(2).once('value',function(snapshot){
var old_data = [];
old_data.push(snapshot.val());
var mystring = JSON.parse(snapshot.val())
return console.log("Old price" + mystring[0].price);
Result : undefined
Looks like you probably will get back an array of up to 2 items from the database because of limitToLast(2). But you need to check if you're actually getting data back from the database before anything else - see the console.log statements below - I have made some other suggestions also.
Try this and see if it solves you issue:
exports.sendBuyerNotification = functions.database.ref('/Bids/{uid}').onWrite((async(change,context) => {
const bid = change.after.val();
console.log(bid) // are you getting a value from this?
const prodid = bid.prodID;
const new_price = bid.price;
const biddata= admin.database().ref('/Bids');
biddata.orderByChild('prodID')
.equalTo(prodid)
.limitToLast(2)
.once('value', function(snapshot){
console.log(snapshot.val()) // check you are getting a value?
const myString = snapshot.val();
console.log("Old price" + myString[0].price);
return {
message: "Old price $" + myString[0].price,
values: snapshot.val()
};
})
})

How to store list of objects for each user in firebase

I'm trying to write an application using firebase. I want to store JSON search objects in searches/ and a reference to each one of them in a table belonging to the user that made the search. Here's my attempt:
var firebase = require("firebase");
firebase.initializeApp(firebaseConfig);
var database = firebase.database();
/*
* Inserts a search into the database
*/
this.addSearchToDB = function(positive, negative, neutral){
let today = new Date();
let dateCreated = today.getFullYear()+"-"+(today.getMonth()+1)+"-"+today.getDate();
var search = {
"query": searchInput,
"location": location,
"until": date,
"dateCreated": dateCreated,
"amount": tweetAmount,
"positive": positive,
"negative": negative,
"neutral": neutral
};
//setup of path to reference the data
var searchesRef = database.ref("searches");
var newSearchKey = searchesRef.push(search).key;
console.log("newSearchRef key:");
console.log(newSearchKey);
let user = firebase.auth().currentUser;
let uid = user.uid;
console.log("Curr user id: "+uid);
let userRef = database.ref("users/"+uid);
let currUserSearches;
userRef.once("value").then( (value) => {
currUserSearches = value;
});
console.log("Current user searches");
console.log(currUserSearches);
if (currUserSearches === undefined)
currUserSearches = [];
currUserSearches.push(newSearchKey);
userRef.set(currUserSearches).then( () => {
database.ref("users/"+uid).once("value").then((value)=>{
console.log(value.val());
});
});
}
On the first insert, this happens:
I get a newSearchKey (logs successfully to console)
I get the user id of the currentUser (logs successfully to console)
currUserSearches is undefined. (logs undefined to console)
In the userRef.set() callback, a list containing newSearchKey is found and printed to the console.
This is all good. It is what I would expect of the first insert. BUT, when I insert again, the exact same procedure repeats itself, meaning that currUserSearches is once again undefined. This is of course wrong. currUserSearches should contain that key that I just inserted. But it seems like it's forgotten what I inserted.
What is going on here, and how can I achieve the behaviour I want?
This is because all queries (read and write) to the Firebase database are asynchronous. The console.log #3 is executed before the userRef.once("value") returns a result.
You should chain the promises, as follow:
let userRef = database.ref("users/"+uid);
let currUserSearches;
userRef.once("value")
.then( (value) => {
currUserSearches = value;
if (currUserSearches === undefined)
currUserSearches = [];
currUserSearches.push(newSearchKey);
return userRef.set(currUserSearches);
})
.then( () => {
return database.ref("users/"+uid).once("value"); // <- Actually could be userRef.once("value")
})
.then((value)=>{
console.log(value.val());
});

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)

firebase nested objects returning null - 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);
}
});

Categories

Resources