Adding/updating data to Parse.com using Javascript - javascript

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
});

Related

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

Given user string input, how to check if object is in array

I'm trying to build a reference bot for discord that can be used to look up information (in this case, cars) and I'm having trouble with a concept. The user is capable of running a command to look up car information. The command the user gives might be $car1, and car1 will be stored in the variable inputCar. The array validCars holds all of the cars that can be looked up, and car1 is one of them. car1 is clearly not a string in this case but an object with multiple fields, but I need to figure out how to be able to look up information on the cars given a string input from the user. My question is twofold:
1) I know that the outer if statement won't work because inputCar is a string that the user entered, and the objects in the validCars array are objects. How can I properly check if what the user enters (in string format) matches the name of one of the objects?
2) Now assuming I can actually determine if the car exists in validCars given the user input, how can I access the fields (name, model, color) given the user input in order to print them?
This might not be the best way to accomplish what I'm trying to do, so any suggestions are appreciated.
var validCars = [car1, car2, car3, car4];
var car1 = {
name:"Corvette Stringray",
model:"2018",
color:"red"
};
/***
*** car2, car3, and car4 all have the same setup as car1, just different values.
***/
// Scan each message (client.on is discord.js jargon)
client.on("message", (message) => {
// Potential car name entered by user (message.content is discord.js jargon,
//it is just returning the string the user entered without the leading command prefix).
// e.g. the value in inputCar might be "car1" if the user wanted to see info on car1.
var inputCar = message.content.substr(1);
// SHOULD check if this is an actual car. This if statement won't work because inputCar is a string,
// and the values in validCars are not strings but objects.
if (validCars.includes(inputCar) == true)
{
// Condition when car1 is entered (there would be other cases for the other cars)
if (message.content == config.prefix + "car1")
{
// Print car1 info including name, model, and color
}
}
else
{
// Invalid car was entered by user.
}
});
You might want to store the cars id with the car in a Map:
const carByKey = new Map([
["car1", car1],
/*...*/
]);
Then its quite easy to get the car:
if(carByKey.has(message)){
const car = carByKey.get(message);
console.log(car.name);
//...
}
If you really want to get the javascripts variable that has the same name and is in global scope, thats possible with window/global (depending on your environment):
if(message in window){
const car = window[message];
}
....But thats a very very bad idea.

how to specify a var field in mongodb find

In mongodb, I want to find a document which exist a field returned by a function.
for example:
var field = func()
var cur = db.test.find({field:{$exists:1}}).limit(1)
Mongodb to find a document has a field named "field", but I want to find a document has a field named the value of the var "field". what shoud I do. Thankd you very much.
Use this
db.CollectionName.find({},{FieldName:1})
in case I want to have results of students who have field named age in their document.
db.CollectionName.find({},{age:1}) // will result all documents with age in their field

how to pass a variable parameter name using ajax

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

Filter Parse Query based on pointer field value

I have two tables A & B, in table B I have a column of type pointer, each field points to a class in table A.
I need to know how to query table B based on the value of a particular field in the pointer column.
So for example, I have 4 objects (records) in table B, and in the pointer column I have pointer1, pointer2, pointer3 and pointer4. So if I want to carry out a query on table B and I want to extract the record with the field value of pointer3 how do I do this in javascript?
Based on your comment I would suggest storing both object IDs for each row. You could use Parse.when(recordA.save(), recordB.save()).then(...) to wait until both finished if you needed to provide feedback in the UI.
An alternative is to just store the object ID for the table B record and in the success handler you'll get back the updated record that'll include the pointer where you can then execute another save. This is slow as it will do two saves in sequence instead of kicking both off at once.
So after a long time searching and looking around and asking questions I figured it out myself in the end. I needed to pass in an object in the query.equalTo method like so:
query.find({
success: function(results) {
var detailsObject = results[0];
detailsObject.set("uuid", uuid);
detailsObject.set("proximity", prox);
detailsObject.set("campaignId", campaignId);
detailsObject.set("location", location);
detailsObject.set("sub_location", subLoc);
detailsObject.save(null, {
success: function(detailsObject) {
var content = Parse.Object.extend("Content");
var contentQuery = new Parse.Query(content);
var id = detailsObject.id;
contentQuery.equalTo("descId", detailsObject);
So "descId" is the pointer column in my content table and rather than trying to query the value in the field (object id of details object), I needed to pass the details object into the query.equalTo
I hope this is of benefit to someone else.

Categories