Update many objects at once in Parse - javascript

I need to update a bunch of objects at once, and I can't find an efficient way to do it all at once since the docs suggest calling .getObjectInBackgroundWithID. I don't have ID's to every object, and even if I did I couldn't pass them all in.
Questions:
1) It would make more sense to call this function in Cloud Code than to handle this all on the client side, right?
2) What's the best way of updating many objects with the same value in a for loop in JS (Cloud Code)/Swift?

I think you're looking for a query with .findObjects (and its variants) then use PFObject's class method .saveAll (and its variants) to save the array of objects.
Here's a sample:
var query = PFQuery(className:"GameScore")
query.whereKey("playerName", equalTo:"Sean Plott")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
println(object.objectId)
// Do your manipulation
}
// Save your changes to ALL objects
PFObject.saveAllInBackground(objects, block: {
(succeeded: Bool, error: NSError!) -> Void in
if (error == nil) {
println("Successfully saved \(objects!.count) objects.")
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
})
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
CloudCode sample:
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("playerName", "Dan Stemkoski");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " scores.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
alert(object.id + ' - ' + object.get('playerName'));
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});

Related

delete entry or update as blank (i.e. " ") to JSON file

I am trying to simply create a delete function, to simply remove the found entry in my JSON file.
So far the below is successfully finding the line (i.e. entry) I want to remove/delete, or update with blank " " - however I am having a hard time writing it back to the JSON file removed... It is fetching just fine, and I am find the line I want to remove just fine.
I believe it is a JavaScript question and something I am mishandling here, as I am using the ../processor.php to write new entries to the JSON file just fine.
// Delete Function
dele.addEventListener('click', ()=>{
let e= document.getElementById("dropdown-of-entry");
let slctn= e.value;
console.log(slctn);
fetch(urld)
.then(
function(response) {
response.json().then(function(data) {
let gData = JSON.stringify(data)
let jsonF = JSON.parse(gData);
let findtempto;
let jsonUpdt;
let jsonUpdtd;
for (let i = 0; i < jsonF.length; i++) {
findtempto = jsonF[i].styleName;
if (findtempto === slctn) {
console.log(jsonF[i]); // This successfully finds the line I want to delete
//delete jsonF[i]; // No avail
jsonF[i] = " "; // Am trying this next
// I have also tried moving the ajax call here, and lines above it
}
}
});
jsonUpdt = JSON.stringify(jsonF);
console.log(jsonUpdt);
jsonUpdtd = JSON.parse(jsonUpdt);
console.log(jsonUpdtd);
$.ajax({
url: './php/data/processor.php',
type: 'POST',
data: { template: jsonUpdtd },
success: function(msg) {
console.log('updated/deleted data');
}
});
}
)
.catch(function(err) {
console.error('Fetch Error -', err);
});
});
Use array.filter() to keep elements in an array that match a criteria.
jsonF = jsonF.filter(e => e.styleName != slctn);
Replacing an object with a string like " " will cause problems later, since the rest of the code expects the array to contain objects.

Creating record using JS and JSON not correctly using owner value

I'm attempt to create a record in Dynamics 365 using JavaScript however the Owner field is not being set properly. The record creates just fine if I remove the setting of the 'ownerid' field. I have also tried formatting the guid both in lowercase and uppercase with no success (see comments in code). The fields are displayed as expected in the alert.
When the script is run both with the code that makes the guid lowercase or not, I get the following error:
Error: An error occurred while validating input paramters: Microsoft.OData.ODataException: A node of type 'StartArray' was read from the JSON reader when trying to read the contents of the property 'ownerid'; however, a 'StartObject' node or 'PrimitiveValue' node with null value was expected.
var managingDirector = Xrm.Page.getAttribute("new_managingdirector").getValue();
var md_id = managingDirector[0].id;
var md_name = managingDirector[0].name
var md_entityType = "systemuser"
//md_id = md_id.replace(/[{}]/g,"");
//md_id = md_id.toLowerCase();
//md_id = "{" + md_id + "}";
if (managingDirector != null) {
console.log(managingDirector[0]);
alert("MD is " + md_name + " with id " + md_id + " and type " + md_entityType);
} else {
alert("MD is null");
}
var md_owner = new Array();
md_owner[0] = new Object();
md_owner[0].name = md_name;
md_owner[0].id = md_id;
md_owner[0].entityType = md_entityType;
var data =
{
"new_name": "Sample Practice Management",
"new_totalamountdue": amountDue,
"new_deductions": deductionAmount,
"new_deductionsnotes": deductionNotes,
"ownerid": md_owner
}
// create pm record
Xrm.WebApi.createRecord("new_practicemanagement", data).then(
function success(result) {
alert("Practice Management record created with ID: " + result.id);
// perform operations on record creation
},
function (error) {
alert("Error: " + error.message);
// handle error conditions
}
);
When I attempt to restructure the data variable like this (with both lowercase and uppercase ID)
var data =
{
"new_name": "Sample Practice Management",
"new_totalamountdue": amountDue,
"new_deductions": deductionAmount,
"new_deductionsnotes": deductionNotes,
"ownerid": {
name: md_name,
id: md_id,
entityType: md_entityType
}
}
I get the following error:
An error occurred while validating input paramters: Microsoft.OData.ODataException: Does not support untyped vvalue in non-open type.
When I see your code you have data i.e field and it's value as below
var data =
{
"new_name": "Sample Practice Management",
"new_totalamountdue": amountDue,
"new_deductions": deductionAmount,
"new_deductionsnotes": deductionNotes,
"ownerid": md_owner
}
Now if you look at my code owner id is set as
entity["ownerid#odata.bind"] = "/systemusers(58127B9D-AFBC-E811-A958-000D3AB42BE8)";
Below is the code which worked for me, I just tried creating contact record.
var entity = {};
entity.firstname = "Webapi1";
entity["ownerid#odata.bind"] = "/systemusers(58127B9D-AFBC-E811-A958-000D3AB42BE8)";
Xrm.WebApi.online.createRecord("contact", entity).then(
function success(result) {
var newEntityId = result.id;
},
function(error) {
Xrm.Utility.alertDialog(error.message);
}
);
To make your life easier w.r.t developement try CRMRESTBuilder you will find most of your code auto generated here.

Result: TypeError: Object [object Object] has no method 'set' when trying to edit Parse object

When I try to run the following background job, I get an error stating Result: TypeError: Object [object Object] has no method 'set', referring to the line where I attempt to set the 'Number' property of the object being returned to a value of 2. I've used this same format to edit Parse objects before, and it worked fine, what am I doing wrong here?
Parse.Cloud.job("sendLowPush", function(request, status) {
Parse.Cloud.useMasterKey();
/////////////
//send push notification to all users in the "lowPush" channel
//{Query the # value of pushIncrement with object id hKj2Eazz6h}
var pushIncrement = Parse.Object.extend("pushIncrement");
var pushIncrementQuery = new Parse.Query(pushIncrement);
pushIncrementQuery.equalTo('objectId', 'hKj2Eazz6h');
pushIncrementQuery.find({
success: function(results) {
for (var i = 0; i < results.length; ++i) {
var dayNumber = results[i].get("Number");
}
console.log('dem results be:' + dayNumber);
//Figure out whether its day 1, 2, or 3, and increment. Send lowPush if day 3.
if (dayNumber = 1){
//change it to 2
console.log('dayNumber is 1');
results.set('Number', '2');
results.save();
}
else if (dayNumber = 2){
//change it to 3
console.log('dayNumber is 2');
}
status.success("Push Notifications completed successfully.");
},
error: function(error) {
console.log('shit');
status.error('shitty shit');
}
});
});
results is the list of objects. You can't set the Number field on the whole list. However, it looks like you are only querying for a single object with a specific ID. In that case you should use .get instead:
pushIncrementQuery.get('hKj2Eazz6h', {
success: function(obj) {
var dayNumber = obj.get("Number");
// ...
obj.set('Number', '2');
obj.save();
}
});
If you want to use .find, you'd have to access the correct element in the list, i.e. either results[i] or results[0].

How to get information from Object in class in Parse.com using JavaScript

I have in parse.com the class MainBranch and it contains objects in columns Customer and Location which are pointing to another classes ((User and locations )) and I need some information from those two classes but I can not reach to them.
My output after running give me [Object Object]
My JavaScript code :
var order = Parse.Object.extend("MainBranch");
var query = new Parse.Query(order);
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " Orders.");
var orid1 = results[2].get("OrderId")
document.getElementById("intro").innerHTML = orid1;
orid1 = results[2].get("Customer");
document.getElementById("intro1").innerHTML = orid1;
orid1 = results[2].get("TotalPrice");
document.getElementById("intro2").innerHTML = orid1;
orid1 = results[2].get("Location");
document.getElementById("intro3").innerHTML = orid1;
orid1 = results[2].get("Date");
var orid2 = results[2].get("Time");
document.getElementById("intro4").innerHTML = orid1+"<br>"+orid2;
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
from my searching I found that relations are necessary thus I tried many ways but i did not undrestand relations clearly and I did not find the solution yet. any help please !!
You can include those objects using
query.include("Customer");
query.include("Location");
This will fetch the related objects together with the MainBranch objects:
var customer = results[2].get("Customer");

SQLITE_ERROR: no such table in Node.js

I'm writing a simple server/client to keep track of the amount of times a user has logged in. A user can create an account and have their count set to 1. Following logins will increase their count in the backend SQLITE3 database.
In the example below, I run the "add" function which correctly checks if the user exists already, then if not, adds the username, password, and 1 to the table of users.
This properly returns 1 as you can see in the output, but why is it erroring at the end? I'm not making any other calls, but it's returning a no such table error. The only call I make is console.log(UsersModel.add('kpam', '123'));, which is on the last line of the code. I tried looking into the line 72 of events.js, but it didn't really give me much. I added print statements to make it trace more obvious, but I have a feeling something is going on behind the scenes?
Basically, I'm confused why if I only called one function, and that function returns successfully, theres an error at the end of execution?
Here is the error returned:
:$ node warmup.js
Creating DB file.
making table!
adding user!
1
events.js:72
throw er; // Unhandled 'error' event
^
Error: SQLITE_ERROR: no such table: Users
:$
And here is my code:
var http = require('http');
var fs = require('fs');
var file = 'data.db';
var exists = fs.existsSync(file);
if (!exists) {
console.log("Creating DB file.");
fs.openSync(file, 'w');
}
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(file);
var UsersModel = {
// success, no errors/problems
SUCCESS: 1,
// cannot find the user/password pair in the database (for 'login' only)
ERR_BAD_CREDENTIALS: -1,
// trying to add a user that already exists (for 'add' only)
ERR_USER_EXISTS: -2,
// invalid user name (empty or longer than MAX_USERNAME_LENGTH) (for 'add'/'login')
ERR_BAD_USERNAME: -3,
// invalid password name (longer than MAX_PASSWORD_LENGTH) (for 'add')
ERR_BAD_PASSWORD: -4,
// maximum user name length
MAX_USERNAME_LENGTH: 128,
// maximum password length
MAX_PASSWORD_LENGTH: 128,
login: function(user, password) {
if (!UsersModel.userExists(user, false)) {
return UsersModel.ERR_BAD_CREDENTIALS;
}
if (!UsersModel.checkPassword(user, password)) {
return UsersModel.ERR_BAD_CREDENTIALS;
}
count = UsersModel.increaseCount(user);
return count;
},
add: function(user, password) {
if (UsersModel.userExists(user, true)) {
return UsersModel.ERR_USER_EXISTS;
}
if (!UsersModel.isValidUsername(user)) {
return UsersModel.ERR_BAD_USERNAME;
}
if (!UsersModel.isValidPassword(password)) {
return UsersModel.ERR_BAD_PASSWORD;
}
UsersModel.addUser(user, password);
return 1;
},
userExists: function(user, makeTable) {
if (!exists) {
if (makeTable) {
console.log('making table!');
db.run('CREATE TABLE Users (name TEXT, password TEXT, count INT)');
}
return false;
}
db.serialize(function() {
console.log('checking user!');
row = db.get("SELECT name FROM Users WHERE name = '" + user + "'");
});
return !(typeof(row.name) === 'undefined');
},
increaseCount: function(user) {
db.serialize(function() {
console.log('increasing count!');
count = db.get("SELECT count FROM Users WHERE name = '" + user + "'") + 1;
db.run("UPDATE Users SET count = '" + count + "' WHERE name = '" + user + "'");
return count;
});
},
addUser: function(user, password) {
count = 0;
console.log('adding user!');
db.run("INSERT INTO Users (name, password, count) VALUES ('" + user + "','" + password + "','" + 0 + "')");
},
checkPassword: function(user, password) {
db.serialize(function() {
console.log('checking pw!');
row = db.get("SELECT password FROM Users WHERE name = '" + user + "'");
});
return row.password == password;
},
isValidUsername: function(user) {
return user.length < 129;
},
isValidPassword: function(password) {
return password.length < 129;
}
}
console.log(UsersModel.add('kpam', '123'));
The db.run(...) calls are asynchronous. So they return immediately, and look like success to your code. However they're still running in the background. Because of this, the SELECT statement is likely starting to run before the CREATE TABLE completes. And that's why you get that error.
I notice that the SELECT statement is inside of a db.serialize(...) call. Unfortunately, that call only serializes statements that are directly inside its scope. All calls outside of the serialize block continue to run in parallel (this includes the INSERT statement that comes up later).
Your code needs to be restructured to use the callbacks that the node sqlite3 module relies on. Take a look at the simple example at:
https://github.com/mapbox/node-sqlite3/blob/master/examples/simple-chaining.js
Notice how the last parameter to each db operation is the name of the function to call after the operation is completed.

Categories