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 }.
Related
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.
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
How can I get a value from an object generated from an input using ng-model for use in my script rather than both the key and value?
So close to solving this problem now that extends from my previous question here Get a value from input to use in controller Angular JS
I've finally managed to prevent a single input value in a table (using ng-repeat) from displaying in each identical location for each row by using the following code:
<input data-ng-model="newEmail[$index]" type="text" id="newEmail" maxlength="254" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" size="20" class="form-control" placeholder="{{user.email}}">
Basically, I need to get the value entered from the ng-model to use in my controller, which I'm currently using like this:
$scope.newEmail = {};
$scope.updateProfile = function (profile) {
setTimeout(function () {
console.log('New email is: ', $scope.newEmail);
}, 1000);
};
The problem I'm getting is that it returns an object as { 1: 'whatever text is entered here' } from the input box. I then simply can not seem to get the value out of the object to update a value in Firebase as it writes both the key and value to the Firebase location I'm trying to write to.
There must be a super simple way to get just the value out of the object that I'm missing?
The input box doesn't return an object. It's because you're not assigning your ng-model just as $scope.newEmail but $scope.newEmail[$index] instead. That's why you get {1: '...'} when you get $scope.newEmail and it is correct.
I don't know what's you use case but why are you initialising newEmail as an object and not just:
$scope.newEmail = null
and then assigning it as:
ng-model="newEmail"
When using Parse, if I have an object called people and two columns, one called name and another called age. The user can input a name to match one that is already stored in Parse, and also input an age to be added to that specific name. How can I get it to search for the name the user has inputted, and if the name matches the user's input, add the age to that specific name?
You cannot save anything in an object unless you have access to its objectId, therefore you need to perform a search as well as a save. You need to find the object(s) associated with the name the user enters and then add age value and save it. The code becomes something like:
var query = new Parse.Query("people");
query.equalTo("name", inputName);
query.find().then( function(objects) { // query and search for object(s)
var person = objects[0]; // get the first object, there can be more than one obviously
person.set("age", inputAge); // set the age
return person.save(); // save the age value in object
}).then(function() {
// success
}, function(error) {
// error
});
trying to invoke a backend php script which reads and writes to a mysql database and would like to define which field (aka column) I want to read or write from/to dynamically.
everything gets thru except the dynamic parameter name which I pass in as field to the javascript function.
if I hardcode field to 'mapstring' (which matches the column name in the mysql database), then it works. But writeabdata.php is written to write to any field name depending on what is passed into it.
What do I have to do to the field string parameter passed into writeabdata() so that it is passed correctly in the data portion of the .ajax call?
function writeabdata(table, id, field, mapstring) {
//alert ("table = "+table+" id = "+id+" field = \'"+field+"\' value = "+value);
$.ajax({
type: 'GET',
url: 'writeabdata.php',
data: {
'table': table,
'id': id,
field: mapstring
},
success: function (data) {
alert ("data Saved "+ data);
}
});
}
Generally when writing you'll want to use the "POST" type rather than the "GET" type. POST is for POSTING data to the data store, and GET is for RETRIEVING it. Without some more code, though, its hard to debug this, so I'm going to take a couple of shots in the dark.
First off, clean up the code a bit and unify your format - put "field" in quotes like your other items. While this may not solve your problem, the JSON standard is actually defined as using DOUBLE QUOTES only.
Second off, if we could see the PHP code, that would help - my guess is that there's something wrong with how the response is interpreted. I suggest that for debug purposes you get Fiddler running and inspect the actual request to make sure that you're sending all required fields to the server.
Once you update us with more info, I can update my answer - but I'd start by switching to POST.
Update
I think I misunderstood the question -- if you're looking to get data.field to really be data.somefield as in the name of that property could change to whatever you want, that's quite simple:
data[field] = mapstring
In other words:
function writeabdata(table, id, field, mapstring) {
//alert ("table = "+table+" id = "+id+" field = \'"+field+"\' value = "+value);
var dataObj = {
'table': table,
'id': id
};
dataObj[field] = mapstring;
$.ajax({
type: 'GET',
url: 'writeabdata.php',
data: dataObj,
success: function (data) {
alert ("data Saved "+ data);
}
});
}
Contrary to some of the comments you got, you can, as you see above, dynamically set property names using the array accessor on an object. And it works swimmingly. Build out your statically named data object properties, and then add the other ones via the array accessor.
You cannot set the field of an object literal (when you use {} directly in your code) using a variable.
For example:
var field = "b";
var myObject = {
"a": "A",
field: "B",
};
That object will look like this:
{
a: "A",
field: "B",
}
The reason this does not work is because fields are always considered to be strings. The fact that you do not need to put quotes around the field names is just language sugar, there to make it look better.
In order to create an object with a custom field you have to use the [] brackets, like this:
var field = "b";
var myObject = {
"a": "A",
};
myObject[field] = "B";
Which will then work as intended:
{
a: "A",
b: "B",
}
Here in your function you are taking 4 arguments- table, id, field, mapstring.. and then making the field:mapstring..
i.e you want the field value to be equal to mapstring than submit.. Why you want to take two arguments in a function to assign one's value to another... May be you just want field as 1 of the field of table.. So take 3 arguments- table, id, field..and assign the value of field similarly you assigned the values of table and id and see if it works...
Also replace GET with POST