how to display firebase val on a html like counter with javascript - javascript

I'm training do display the current value from my firebase database
on to my HTML counter.
the problem is that I see only the current clicks and not the total clicks
in the console, I can see the database value + 1
var bunnyData = null;
function thumbsUpBtn(val) {
var count = document.getElementById('like').value;
var new_count = parseInt(count ,10) + val;
if (new_count < 0) {
new_count = 0;
}
var videosList = firebase.database().ref().child('videos');
videosList.on("value", function(snapshot) {
var allVideos = snapshot.val();
bunnyData = allVideos.bunny;
console.log( bunnyData.likeCount);
WriteStatsToPage();
});
onclick
videosList.child("bunny").set({
likeCount : bunnyData.likeCount+1,
dislikeCount : bunnyData.dislikeCount,
viewsCount : 100
});
function WriteStatsToPage(){
$("likeNUmber").html[bunnyData.likeCount];
}
document.getElementById('like').value = new_count ;
return new_count ;
}
<button id="thumbsUp" onClick="thumbsUpBtn(1)">
<img class="likeImg" src="Like.png" >
<input id="like" value="0" ></button>

Transactions and Batched Writes
Transactions are useful when you want to update a field's value based
on its current value, or the value of some other field. You could
increment a counter by creating a transaction that reads the current
value of the counter, increments it, and writes the new value to Cloud
Firestore.
A transaction consists of any number of get() operations followed by
any number of write operations such as set(), update(), or delete().
In the case of a concurrent edit, Cloud Firestore runs the entire
transaction again. For example, if a transaction reads documents and
another client modifies any of those documents, Cloud Firestore
retries the transaction. This feature ensures that the transaction
runs on up-to-date and consistent data.
// Create a reference to the SF doc.
var sfDocRef = db.collection("cities").doc("SF");
// Uncomment to initialize the doc.
// sfDocRef.set({ population: 0 });
return db.runTransaction(function(transaction) {
// This code may get re-run multiple times if there are conflicts.
return transaction.get(sfDocRef).then(function(sfDoc) {
var newPopulation = sfDoc.data().population + 1;
transaction.update(sfDocRef, { population: newPopulation });
});
}).then(function() {
console.log("Transaction successfully committed!");
}).catch(function(error) {
console.log("Transaction failed: ", error);
});

Related

Trying to limit my results and sort my data, from MongoDB using NodeJS

I am using MongoDB and Node.JS, I am trying to get data out of my MongoDB and show into my html page which I have working with the below code however this just brings back ALL entries in no particular order:
server.js
// This is for getting the list of all players from my DB
app.get("/getPlayers", function(request, response) {
db.getPlayers().then(function(players){
console.log(players);
response.send(players);
});
});
leadership.html
<script>
$(function() {
$.get("http://localhost:9000/getPlayers", {}, function (res) {
let data = res;
console.log(res);
for (i = 0; i < data.length; i++) {
let name = data[i].name;
let score = data[i].score;
console.log(data[i].name);
$("#leadership").append("<tr><td class=\"name\">"
+ data[i].name + "</td><td class=\"score\">"
+ data[i].score + "</td></tr>");
}
});
});
</script>
After looking at W3 Schools I tried to alter the code to this:
db.getPlayers().sort().limit(10).then(function(players)
However my Chrome console brings back an internal server error 500. Can someone point out how I can sort by LARGEST NUMBER first, then LIMIT the results to say 10? Within the database there is a collection called players, which holds name and score
db.js
var Player = mongoose.model("Player", {name: String, score: Number});
module.exports.Player = Player;
Try something like this.
Order, sort and limit can be passed from front end or change default values after : mark.
Players is imported model, you can do it this way or use method in the model itself.
app.post('/api/players',(req,res)=>{
let order = req.body.order ? req.body.order : "-1";
let sortBy = req.body.sortBy ? req.body.sortBy : "_id";
let limit = req.body.limit ? parseInt(req.body.limit) : 100;
Players.
find().
sort([[sortBy,order]]).
limit(limit).
exec((err,players)=>{
if(err) return res.status(400).send(err);
res.status(200).json({
size: players.length,
players
})
})
})

SAPUI5 odata.v2.ODataModel Call back of batch request is invoked before batch request is complete

I'm having a little issue with my batch request, when the odata model is submitted and triggered, the that.readAndUpdateSercicePeriodPlans(oService).then(function(oSerciceO) in the callback is triggered before the batch return the result
As you can see using my debugger, the call back function is triggered :
but the network didn't return the result yet :
Below is the code, what I am doing wrong? :
odataMod = this.getModel("Service");
odataMod.setUseBatch(true);
var aDeffGroup = odataMod.getDeferredGroups();
//add your deffered group
aDeffGroup.push("deletionGroup");
_.forEach(periodPlanArr, function(periodPlanToDel) {
odataMod.remove('/ProjectTaskServicePeriodPlanCollection(\'' + periodPlanToDel.ObjectID + '\')/', {
groupId: "deletionGroup"
});
});
oGlobalBusyDialog.setText("Deleting Period Plans in progress");
oGlobalBusyDialog.setTitle("Updating data Model");
oGlobalBusyDialog.open();
//This trigger the batch request
odataMod.submitChanges({
// deffered group id
groupId: "deletionGroup",
success: function(oData) {
sap.m.MessageToast.show(oData.toString());
var aErrorData = sap.ui.getCore().getMessageManager().getMessageModel();
var msg = aErrorData.getData();
var oService = _.find(oNoneAssignedTaskModelData, function(oSewrv) {
return oSewrv.ObjectID === uniqueByID[0].ParentObjectID;
});
oGlobalBusyDialog.setText("Updating oModel in progress");
oGlobalBusyDialog.setTitle("Updating data Model");
// ISSUE : This below function is invoked before even the batch request is complete , why ?!
that.readAndUpdateSercicePeriodPlans(oService).then(function(oSerciceO) {
oGlobalBusyDialog.close();
//Logic USER STORY 3423: Get Internal Indicator PeriodPlan and update the employee nternal Indicator PeriodPlan
},
error: function(oError) {
var oResponse = JSON.parse(oError.response.body);
sap.m.MessageToast.show("Fehler: " + oResponse.error.message.value);
}
});
Your Chrome Filter icon will only be red if there is some value in the filter.:)
After debugging all night and drinkind redbull I've finally found the issue :
var aDeffGroup = odataMod.getDeferredGroups();
aDeffGroup.push("deletionGroup");
//I must set the deffered groups after pushing the ID or else it won't be added
this.setDeferredGroups(aDeffGroup);
I'd recommand to avoid adding same group twice - I had some issues because of that.
odataMod = this.getModel("Service");
odataMod.setUseBatch(true);
//var aDeffGroup = odataMod.getDeferredGroups();
//aDeffGroup.push("deletionGroup");
that.setModelDeferredGroup(odataMod, "deletionGroup");
// the function
setModelDeferredGroup: function (oModel, sGroup) {
if (oModel && sGroup) {
var aDeferredGroups = oModel.getDeferredGroups();
if (aDeferredGroups.indexOf(sGroup) < 0) {
aDeferredGroups.push(sGroup);
oModel.setDeferredGroups(aDeferredGroups);
}
}
}

web based firebase code running multiple times when executed

I am trying to update some data into my Firebase realtime database, but for some reason the code runs multiple times when i present it with a new string, this messes up the output of the code.
Below is what I have tried, I tried to create a new function for the ref.update(), but the same thing happens again, I have pointed in the comments of the code where exactly the code goes back to.
function fire_base_db() {
var ref = firebase.database().ref();
ref.on("value", function(snapshot) {
r = snapshot.val();
var ham_db = r.hams.spam_words;
var spam_db = r.spams.spam_words; //contains spam data now
console.log('function 1')
inputstring(ham_db, spam_db);
}, function(error) {
console.log("Error: " + error.code);
});
}
inputstring(ham_db, spam_db); //just a random function i need
spam_prop(user_string_toknized, spam_db, ham_db); //yet another
function spam_or_ham()
function spam_or_ham() {
var final_value = " ";
if (total_spam_probablity < total_ham_probablity) {
console.log("ham");
final_value = "ham";
} else {
console.log("spam");
final_value = "spam";
}
if (final_value = "spam") {
var ref = firebase.database().ref("hams/spam_words/");
ref.update(old_words_spam_2);
} else if (final_value = "ham") {
var ref2 = firebase.database().ref("spams/spam_words/")
ref2.update(old_words_ham_2)
};
for (var a in new_words_spam) {
new_words_spam[b] = 1
}
for (var b in new_words_ham) {
new_words_ham[a] = 1;
}
if (final_value = "spam") {
var ref9 = firebase.database().ref("spams/spam_words/")
ref9.update(new_words_spam)
} else if (final_value = "ham") {
var ref2 = firebase.database().ref("hams/spam_words")
ref2.update(new_words_ham)
}
}
fire_base_db_upadt_new_words();
fire_base_db_upadt_new_words_2();
The first function fire_base_db() is used to read data from the database, the next 2 functions are just some steps for the output, the last function spam_or_ham is where the bug appears, moment the code enters the if statement and reaches the ref9.update part, it runs back to ref.on in the first function and run multiple times, each time executing till the ref9 part, except in the last execution where the whole code is executed, I want the full code to be executed in the first time itself.

Node.js giving empty array for dependent queries

I have PHP website in which, chat module is working fine ( via ajax ).
Now I am creating Ionic app for this chat module, So I am trying to convert my PHP code on NODE.js
To get a list of chat users i wrote this code in helper.js file
setMessage:function(message1){
message=message1;
},
setPeople:function(id,people1){
people[id]=people1;
},
setChatlist:function(data9){
chatlist.push(data9);
},
setRecorder:function(data8){
recorder.push(data8);
},
getUserChatList:function(uid,connection,callback){
chatlist=[];
recorder=[];
people=[];
message={};
var data={
query:"select id from messages where recipient_id='"+uid+"' or timeline_id='"+uid+"' order by timestamp desc ",
connection:connection
}
var db_conncetion=data.connection;
var query=data.query;
var insert_data=data.insert_data;
db_conncetion.getConnection(function(err,con){
if(err){
con.release();
}else{
con.query(String(query),insert_data,function(err,rows){
if(!err) {
if(rows.length>0){
query1="select DISTINCT recipient_id from messages where timeline_id='"+uid+"' order by timestamp desc ";
con.query(String(query1),insert_data,function(err1,rows1){
rows1.forEach(function(element1, index1, array1){
var receiverId=element1.recipient_id;
var receiverSql = "SELECT time,text FROM messages WHERE timeline_id=" +uid+ " AND recipient_id=" +receiverId+" ORDER BY time DESC";
con.query(String(receiverSql),insert_data,function(err2,rows2){
rows2.forEach(function(element2, index2, array2){
people[receiverId]=element2.time;
message[receiverId]=element2.text;
});
self.setMessage(message);
self.setPeople(people,people);
});
});
});
var senderIdSql = "SELECT DISTINCT timeline_id FROM messages WHERE recipient_id=" +uid+ " ORDER BY time DESC";
con.query(String(senderIdSql),insert_data,function(err3,rows3){
rows3.forEach(function(element1, index1, array1){
var senderId=element1.timeline_id;
var senderSql = "SELECT time,text FROM messages WHERE recipient_id=" +uid+ " AND timeline_id=" +senderId+ " ORDER BY time DESC";
con.query(String(senderSql),insert_data,function(err2,rows2){
rows2.forEach(function(element2, index2, array2){
if (!self.isset(people[senderId]) || element2.time > people[senderId])
people[senderId]=element2.time;
message[senderId]=element2.text;
self.setPeople(senderId,element2.time);
self.setMessage(message);
});
});
});
});
}
Object.keys(people).forEach(function (key){
var tempArray={};
tempArray['id']=key;
tempArray['text']=message[key];
self.setRecorder(tempArray);
});
recorder.forEach(function (key){
var user_query="SELECT * FROM accounts WHERE id=" +key +" AND active=1 ";
con.query(String(user_query),insert_data,function(err3,rows3){
var tmp1=[];
rows3.forEach(function(element2, index2, array2){
var data1={};
data1['receiver_id']=element2.id;
data1['receiver_username']=element2.username;
data1['receiver_name']=element2.name;
data1['receiver_thumbnail_url']=element2.thumbnail_url;
data1['receiver_online']=0;
data1['receiver_message'] = recorder[key];
tmp1.push(data1);
});
self.setChatlist(tmp1);
});
});
var ret_data={};
ret_data['status']=200;
ret_data['success']=1;
ret_data['messages']=chatlist;
console.log(ret_data);
console.log("1111");
callback(ret_data);
con.release();
//console.log(message);
} else {
console.log(err);
console.log("Query failed");
}
});
}
});
}
But when i am calling this method via socket it's giving an empty array
listening in http://localhost:3000
{ status: 200, success: 1, messages: [] }
1111
Please tell why it's giving an empty array?
It is supposed to be an empty array according to your current code.
All the db calls will be asynchronous and will not wait for its completion. It will execute the next line which will execute the following code before the db calls get finished:
var ret_data = {};
ret_data['status'] = 200;
ret_data['success'] = 1;
ret_data['messages'] = chatlist;
console.log(ret_data);
console.log("1111");
callback(ret_data);
con.release();
//console.log(message);
So your callback gets executed with initial value that is [] and thus you have the value as [].
You have to manage the db calls and the data to be sent. You can use promises or async/await to this. The code will be much more clean and traceable. Take a good look at them.

Fetching and displaying data from Firebase takes time

I'm reading value of pid from Firebase database and then using this pid value, I'm fetching further values from the database.
//fetching pid
firebaseRef.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
//getting key of the child
var pid = childSnapshot.key;
// childData will be the actual contents of the child
var childData = childSnapshot.val();
pid[i].id = "pid" + (i + 1);
document.getElementById(pids[i].id).innerText = pid;
i++;
});
});
//displaying marks
var pid1 = document.getElementById("pid1").innerHTML;
guideRef = firebase.database().ref("internal").child(pid1).child("guide");
guideRef.child("report").once('value').then(function(snapshot) {
document.getElementById(reportGuideMarks).value = snapshot.val();
});
But runnning this code I get this error:
Uncaught Error: Firebase.child failed: First argument was an invalid path: "". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"
The pid error is due to pid1 being null. But when I put delay of 3 seconds on the 'displaying marks' part, the code runs perfectly.
The displaying marks executes even before the values of pid have been set.
It takes a few seconds to set the value of pid in the table.
What is the issue? Why does it take so much time to load values of database? Or is it an issue with setting the value?
Requests to firebase are asynchronous so the "displaying marks" code will run before the "fetching pid" code has completed.
You could add another then() so the second part won't run until the first part has completed
//fetching pid
firebaseRef.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
//getting key of the child
var pid = childSnapshot.key;
// childData will be the actual contents of the child
var childData = childSnapshot.val();
pid[i].id = "pid" + (i + 1);
document.getElementById(pids[i].id).innerText = pid;
i++;
});
})
// new then() won't fire until prior then() is completed
.then(function() {
//displaying marks
var pid1 = document.getElementById("pid1").innerHTML;
guideRef = firebase.database().ref("internal").child(pid1).child("guide");
guideRef.child("report").once('value').then(function(snapshot) {
document.getElementById(reportGuideMarks).value = snapshot.val();
});
})

Categories

Resources