How to update fields in Firestore map - javascript

Don't know how to go about adding new fields into a map in Firestore using a variable rather then a hardcoded field name.
I have a data structure in firestorm. The collection is called webQuiz and the document is called '12345. The data structure looks like:
roomName: Demo0
roomNumber: 46532
people:{11111:"David, 22222:"Peter}
Note that people is a map data object.
I would like to add another field to the people map. The code below works but instead of the data looking like
people:{11111:"David, 22222:"Peter, 44444:"Cathy"} it looks like
people:{11111:"David, 22222:"Peter, x:"Cathy"}
How can I use a variable which holds the field name in this situation? The x should be a variable but it is picked up literally as a property.
function testing(){
var x = "44444"
var y = "Cathy"
var cityRef = db.collection('webQuiz').doc('12345');
var setWithMerge = cityRef.set({
people: {x: y}
}, { merge: true });
I expect the output in firestorm to be
people:{11111:"David, 22222:"Peter, 44444:"Cathy"} but the actual output at the moment is
people:{11111:"David, 22222:"Peter, x:"Cathy"}
Thanks

You'll need to use the full field path as the key of the update:
var setWithMerge = cityRef.set({
`people.${x}`: y
});
This will prevent re-writing the entire "people" field, since you are specifying which property of the map to change directly.
Note that the field name and the property name are separated by a period.

Related

how to show data after parse json

I try to load the list of users in the following code
<div id="users" data-users='[{"name":"one","userName":"user_one"},
{"name":"two","userName":"user_two"},{"name":"three","userName":"user_three"}]'></div>
How can I load the list of users in the values?
const users = document.querySelector("#users");
const json = JSON.parse(users.dataset.users);
var tribute = new Tribute({
values: ** Load users this line **
});
I see that you are assigning the result of JSON.parse(users.dataset.users) to the constant "json". This leads me to think you may misunderstand the resulting value from JSON.parse.
The data-set value on the div is currently json, so document.querySelector("#users") will return the json value.
JSON.parse(users.dataset.users) will then convert the json (users.dataset.users) into a JavaScript value, in this case returning the array of users I believe you wish you assign to the values property in the Tribute constructor.
I've switched your variable names below to make this more clear.
const json = document.querySelector("#users");
const users = JSON.parse(json.dataset.users);
let tribute = new Tribute({ values: users });
* As "the_previ" pointed out, without the definition for Tribute it's unclear to us what value the "values" property expects (ie. String, Number, Array). I've assumed you're looking to pass in the array of users.
It's actually very simple using Lodash!
You just need to import Lodash, and use the map function:
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
<script>
const users = document.querySelector("#users");
var json = JSON.parse(users.dataset.users);
const userlist = (_.map(json, "name"));
</script>
userlist will be an array containing every "name" value.
If you want to use userName values instead, just replace name with userName on the map function!

Firebase update field using variable in javascript

I have a function which should go ahead and update the database on firebase
function editUser() {
var userID = document.getElementById('userID').value;
var editUserField = document.getElementById('editUserField').value;
var newUserValue = document.getElementById('newUserValue').value;
var database = firebase.database().ref().child('users/' + userID);
database.once("value", function(snapshot){
console.log(snapshot.val());
})
database.update({
editUserField: newUserValue
})
}
The above code is sort of working. Its getting the correct user, but whats not happening is the field is not getting updated, but instead, its creating a new field in the database and assigning it the value.
Looks like a key pair value is getting passed in
editUserField: newUserValue
but its actually taking the value editUserField
rather than getting getting it from the input:
var editUserField = document.getElementById('editUserField').value;
The value is actually getting stored correct from:
var newUserValue = document.getElementById('newUserValue').value;
But it doesnot update the value for the correct key, instead creates a new field called editUserField
I need it to get the values from the input and update the fields in firebase.
If I understand your intentions correctly, you want the field that is updated to be the value of editUserField.
As an example, if editUserField is "favorite-food" and newUserValue is "pizza", you want { favorite-food: pizza } to be added to the user's data.
If that's the case, you were very close, you just need to wrap editUserField in square brackets to use it's value:
database.update({
[editUserField]: newUserValue
})
Note: Don't forget to sanitise editUserField! You wouldn't want them setting { isAdmin: true }.

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.

How can I create an object or array of array data in JS with key named elements?

I have an array called values. At present, I'm appending new data to this array as such:
values.push(guests);
The result of my array is something like this:
["123456789", "Joe", "Bloggs", "Test Corp", "fiji", true, "guest, guest 2, guest 3", true]
I have now realised that in its present state this data is useless to me as I cannot tell what each element is. In my example above, the first long number is an account number and the second element is a first name but these are liable to change. E.g the company name Test Corp may not always exist in the data. This means I cannot use the numerical key [3] to target it because it may not be present.
Therefore I need to code this data into something that I can assign both a label for the data, and the data value. I'm guessing the best way to do this would be with an JSON object.
How can I create a key->value pair object? I would need to replace my .push() code above to instead add the value of COMPANY NAME -> Test Corp so that it can be deciphered later.
For reference, I am then stringifying this data and using an AJAX request to POST it to a PHP script where it will need to be arranged into variables e.g $company_name = 'Test Corp';
You're talking about a plain JavaScript object. JSON is a transfer format inspired by JavaScript syntax.
To make an object, just initialize a variable:
var values = {};
And add properties:
values.accountNumber = "123456789";
values.firstName = "Joe";
etc. If you know the properties up front and have values available, you can make the object in one step:
var values = {
accountNumber: "12345678",
firstName: "Joe",
// ...
};

Categories