adding data to firebase realtime database from an object (web) - javascript

I have an object containing multiple key value pairs, I want to add all the keys and their values, from inside the object to an existing node, without disturbing the data already present inside the node.
If i write like this
var ref = firebase.database().ref("hams/spam_words/");
ref.update({
new_words_ham //new_word_ham is an object containing n number of words
});
it will add new_words_ham as another child node inside the main node , i cannot have that
even using a forloop on the object does not work
var ref = firebase.database().ref("hams/spam_words/");
for(var i in new_words_ham){
var word = i
ref.update({
i
});
I am new to js as well as to firebase. Please do tell me if i have got any concept wrong

Your existing code
//new_word_ham is an object containing n number of words
firebase.database().ref("hams/spam_words/").update({
new_words_ham
});
Can be rewritten as
firebase.database().ref("hams/spam_words/").update({
new_words_ham: new_words_ham
});
when the shorthand syntax is expanded. What I believe you want is simply
firebase.database().ref("hams/spam_words/").update(new_words_ham);

Related

Check if firebase array contains value then get all data in that index

So I have an array in a firebase document called ActivityLikes. It looks like this:
The collection is like this below:
const db = fire.firestore();
db.collection("eventLikes")
.doc(eventID)
.set({
ActivityLikes: likes
})
I have another collection which has the word "Avoca" saved, and I have this right now and I basically want to pull the data that has "Avoca" in it. So like with the name "Avoca" i can also get the imgURL. I've tried a for loop to go inside the object that firebase returns but I guess my logic is due to the fact theres multiple value and key pairs inside of it so how would i get all of the data inside of index 1 because it has the name = "Avoca".
I have the activitylikes in a hook so I have it after calling it from firebase.
I've tried like:
for (var i=ActivityLikes.length; i--;) {
if (myArr[i].indexOf("Avoca")>=0) break;
}
I think my logic is off Im just not sure how to get all of the data inside of the index once the name matches
The other collection just looks like this: https://i.stack.imgur.com/TqhWd.png. I know how to call this from firebase, I just need to figure out the logic for getting all the data in the array in the ActivityLikes when the name "Avoca" is present
If you are looking just for the word "Avoca" then try using find():
// data is snapshot.data() after query
const avocaData = data.ActivityLikes.find(d => d.name === "Avoca")
Here avocaData will either be the first object from likes array where name is Avoca or undefined is there isn't any. After that you can use an if statement to check that and proceed with rest of the logic.

JavaScript FormData Sort Entries (without jQuery)

I have some code that uses jQuery and needs re-writing to use native JS but I am having trouble with one section of it where what it does is:
Obtains the form data
Sorts the keys alphabetically
Loops through the elements to create a new array of items based on the form
This is what works in jQuery:
let formData = $('#TheForm').serialize();
let formItems = formData.split("&");
formItems.sort();
for (const element of formItems) {
//Do stuff here
}
This is what I have so far in native JS that does not yet work:
var theForm = document.getElementById('TheForm');
let formData = new FormData(theForm);
let formItems = formData.entries();
//formItems.sort(); <-- Can't work out a way to do this
for (let [key, value] of formItems) {
//Do stuff here
}
I think once I can figure out a way to sort the entries this will hopefully work and the code in the for loop can be simplified as it is having to extract the key and value on the = sign (from element) currently but in the new version the key and value are already separate.
The reason I am sorting the keys is because this form submits to the Barclays payment system (EPDQ) and requires the form elements to be in alphabetical order and I must also encrypt them, sending both the unencrypted and encrypted values where the server only accepts the data if the encrypted version matches when the remote server performs the same function. Within the loop I am populating both encrypted and unencrypted arrays so it is easier to sort at this point rather than later.
Thanks I really appreciate the help (below).
Since the entries function returns an Iterator, you'll first want to get an Array from that:
const formItems = Array.from(formData.entries())
At this point you have an Array of pairs, each pair being a tuple, an Array where the first element represents the "key" and the second one the "value". This is good though, because you now have an array on which you can call the sort function, that just so happens to be able receive a comparator function!
const sortedItems = formItems.sort(
([leftKey], [rightKey]) => leftKey > rightKey ? -1 : 1
)
The sort function is receiving an arrow function, where the two parameters (the two items being compared) are destructured in order to extract the first value of each of them into a variable - each of them being a pair, an array of two values, this works out just fine.

Updating all fields in an document using a Javascript object

I want to update all the fields in a MongoDB document and I have a Javascript object that contains all these fields. I could easily type out each field to update but this seems like a lot of manual work and not reusable. I wanted to do something like below but this creates an object containing all the new field data within the document called newData.
I've tried JSON.stringify on the variable but the format isn't appropriate for update.
var newData = {
_id:ObjectId("53245234..."),
id: 88888,
firstData: "someData",
secondData: 787855,
thirdData: [ 45,17,12,234]
};
var collection = db.get('CollectionToUpdate');
//strip out dB id so as not to overwrite it, possibly not needed
if ("_id" in newData) {
delete newData["_id"];
}
//find the correct document based on program generated id and update
collection.update({id: newData.id}, {
newData
})
If you trust newData will not have any keys you don't intend (like update operators) this should work:
var collection = db.get('CollectionToUpdate');
collection.update({id: newData.id}, newData)
Note that this replaces the document. I assume that is what you meant by "update all the fields". update does not replace "_id".
Documentation for update

Insert data in Firebase in Reactjs

During storing an object to my firebase, I am expecting the structure as image below, but what I get was a generated running number as a key. This is my code to store an object to firebase
var location = [];
location.push({
ms_jhr_1 : {
name: value
},
...
});
const a = firebase.database().ref('Food/'+id);
a.set(location);
How do I keep my structure without generate the running number?
The problem is you are using an array to store your data and then setting that array in firebase. To get the expected result you have to modify your code a little bit.
Here use this and remove other code
const a = firebase.database().ref('Food/'+id);
a.set(ms_jhr_1);
So you just need to pass the object you want to store under that id and not the whole array.
Note:- If you want to store multiple entries under one id then you have to push all those entries in an Object and not in array.
So it will look something like this
var location = {};
Now use for loop to insert all your data into this object (Remember, you are adding objects inside an object). You don't need array. Because in firebase data is stored in JSON tree format.
Hope it helps.

Firebase: How to force database to store values in the order they are entered?

At the moment, Firebase doesn't stores the data in the order it is entered. For ex - There could be 2 existing childs and a new child is inserted, that new child goes and sits in the middle of the already existing ones! I guess this works by alphabet order but I want to store data in the correct order only.
firebase.database().ref('someChildRef').set({
//Could insert anywhere
});
I think push could insert it in the correct order but push also generates a unique key which I don't want, I want to insert data only using set and in the correct order.
It is not possible to insert data into Firebase into a desired position. Firebase data is sorted alphabetically and all newly inserted data will be rearranged accordingly.
Use query rules to return the data in the order you want.
Such as:
orderByChild()
orderByKey()
orderByValue()
equalTo()
You are correct about push(), it will always create a unique key and add to the end, just as pushing to an array will add to the end.
It sounds like you're looking for Firebase's push() method, which generates a unique key based on the timestamp:
firebase.database().ref('someChildRef').set({
//Will result at "the end"
});
var messageListRef = new Firebase('https://samplechat.firebaseio-demo.com/message_list');
var newMessageRef = messageListRef.push();
newMessageRef.set({ 'user_id': 'fred', 'text': 'Yabba Dabba Doo!' });
// We've appended a new message to the message_list location.
var path = newMessageRef.toString();
Try using the push() method instead of set. According to their docs:
The unique name generated by push() is prefixed with a client-generated timestamp so that the resulting list will be chronologically-sorted.
Reference: https://www.firebase.com/docs/web/api/firebase/push.html

Categories