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()
};
})
})
Related
I am building a mongoose query and storing it in a variable call query. The code below shows it
let query = "Product.find(match)";
if (requestObject.query.sortBy) {
query = query.concat(".", "sort(sort)");
const parts = requestObject.query.sortBy.split(":");
sort[parts[0]] = parts[1] === "desc" ? -1 : 1;
}
if (requestObject.query.fields) {
query = query.concat(".", "select(fields)");
const fields = requestObject.query.fields.split(",").join(" ");
const items = await Product.find(match).sort(sort).select(fields); //.populate("category").exec();
/**const items = await Product.find(match).sort(sort).select("-__v"); //.populate("category").exec();**/
}
I am facing an issue when attempting to run a mongoose query that I have generated and stored in a string. When I run it in post man, the response is 200 but no data is returned. Below is a console.log(query) on line 2
what I hope to achieve is to have await or create a new promise execute the content id query variable like shown below
const items = new Promise((resolve) => resolve(query)); //.populate("category").exec();
items
? responseObject.status(200).json(items)
: responseObject
.status(400)
.json({ message: "Could not find products, please try again" });
I will appreciate it very much that and also if you can give me a better way of doing it, I will love that
This doesn't really make sense. You are building a string, not a query. You can't do anything with that string. (You could eval it, but you really shouldn't). Instead, build a query object!
let query = Product.find(match);
if (requestObject.query.sortBy) {
const [field, dir] = requestObject.query.sortBy.split(":");
const sort = {};
sort[field] = dir === "desc" ? -1 : 1;
query = query.sort(sort);
}
if (requestObject.query.fields) {
const fields = requestObject.query.fields.split(",");
query = query.select(fields);
}
//query.populate("category")
const items = await query.exec();
if (items) {
responseObject.status(200).json(items)
} else {
responseObject.status(400).json({ message: "Could not find products, please try again" });
}
If you really want to get that string for something (e.g. debugging), build it separately from the query:
let query = Product.find(match);
let queryStr = 'Product.find(match)';
if (requestObject.query.sortBy) {
const [field, dir] = requestObject.query.sortBy.split(":");
const sort = {[field]: dir === "desc" ? -1 : 1};
query = query.sort(sort);
queryStr += `.sort(${JSON.stringify(sort)})`;
}
if (requestObject.query.fields) {
const fields = requestObject.query.fields.split(",");
query = query.select(fields);
queryStr += `.select(${JSON.stringify(fields)})`;
}
//query.populate("category")
//queryStr += `.populate("category")`;
console.log(queryStr);
const items = await query.exec();
…
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.
I need help with pushing 2 data values into localStorage. I know a little about the stringify and parse methods but cant grasp how to implement them.The 2 data values are from "Scores" and "saveName"(a username that is put into an input box).
var Score = (answeredCorrect * 20) + (timeleft);
var saveName = document.querySelector("#saveName");
function Storage() {
localStorage.setItem("User", JSON.stringify(saveName.value));
localStorage.setItem("Scores", JSON.stringify(Score));
var GetStorage = localStorage.getItem("User");
var GetStorage2 = localStorage.getItem("Scores");
return {
first:console.log("GetStorage: "+ GetStorage + GetStorage2),
second:GetStorage,
third:GetStorage2,
};
};
var values = Storage();
var first = values.first;
var second = values.second;
var third = values.third;
As mentioned in the comments you need to parse it once retrieved from storage with JSON.parse, also naming Storage should be avoided.
Since your making a wrapper for localstorage, it could be done like this:
const Store = {
set: (key, value) => localStorage[key] = JSON.stringify(value),
get: key => JSON.parse(localStorage[key])
}
Then you can simply call it like the following, with a set and get methods:
//
Store.set('Score', Score)
Score = Store.get('Score')
//
Store.set('User', saveName.value)
saveName = Store.get('User')
Though you only need to get() on page load as you already have the value in Score/saveName etc.
I'm trying to sort and display firebase data however I'm stuck. My database looks like this :
I need to sort the data by nr_of_matches and I can do that by querying like this :
const ref = firebase.database().ref('Matches/'+db_name).orderByChild('nr_of_matches')
ref.once('value', function (snapshot) {
snapshot.forEach(function (childSnapshot) {
const matches = childSnapshot.val().matches
const nr_of_matches = childSnapshot.val().nr_of_matches
const the_matched = childSnapshot.val().the_matched
console.log("matches : "+matches)
});
});
However, I retrieve repeated data doing it like this.
To not get repeated data I can do it like this:
const ref = firebase.database().ref('Matches/'+db_name+"/"+child.key).orderByChild('nr_of_matches')
ref.on('value', function (snapshot) {
const matches = snapshot.val().matches
const nr_of_matches = snapshot.val().nr_of_matches
const the_matched = snapshot.val().the_matched
console.log("matches : "+matches)
});
but then it's not sorted anymore. Any idea how do sort this out?
If you dont want to retrieve repeated data, then you can use a query:
const ref = firebase.database().ref('Matches/'+db_name+"/").orderByChild('nr_of_matches').equalto(2);
ref.on('value', function (snapshot) {
const matches = snapshot.val().matches
const nr_of_matches = snapshot.val().nr_of_matches
const the_matched = snapshot.val().the_matched
console.log("matches : "+matches)
});
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);
}
});