Invalid Object Name error in Parse JavaScript SDK - javascript

I am using Parse as a service for my app, specifically the JavaScript SDK.
In my app I have a class that represents a user post in my app containing images and text.
For some reason occasionally when a new object is created by the user, the objectId assigned by parse sometimes causes errors with that particular post.
I get this in the console:
t.Error {code: 105, message: "invalid field name: 3qUHMBPCBs"}
the field name is the objectId assigned automatically by Parse when the user uploads their post.
Second time this has happened. I noticed when I removed that post, the error disappeared but, obviously I can't keep deferring to that method.
Updated, code used for the user post below
so, essentially theres functionality that allows a user to post an update to parse. When the user submits, this function is performed and an object is generated by Parse.
var sendThis = $('#resultImage').attr('src');
var parseFile = new Parse.File("mypic.jpg", {
base64: sendThis
});
var val = document.getElementById('statusupdateform').value;
var statusupdate = $('#statusupdateform').val();
var currentUser = Parse.User.current();
parseFile.save().then(function() {
var nameCurrent = currentUser.getUsername();
var cigarWall = new Parse.Object("cigarwall");
cigarWall.set("appuser", nameCurrent);
cigarWall.set("statusupdate", statusupdate);
cigarWall.set("imagefile", parseFile);
cigarWall.save({
success: function() {
$('#uploadBtn').removeClass('tapActive');
var postupdate = cigarWall.get('statusupdate');
//$('#fileselect').attr('data-change', 'false');
$('#statusInnerWrapper').removeClass('slideLeft');
location.reload();
},
error: function() {
alert("upload failed. please try again!");
}
});
});

I Had a bad line of code in my Query function for one of the Parse classes. I Was unnecessarily querying against the objectId column.

Related

Parse Cloud Code. Unable to define relation

I am calling this function from my android app,
Parse.Cloud.define('addFriendRequest', function(request, response) {
var userObjectId = request.params.userObjectId;
var User = Parse.Object.extend('_User'),
user = new User({ objectId: userObjectId });
var relation = Parse.Relation(user, 'friendRequests');
relation.add(request.user);
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success("Successfully added friend Request");
}, function(error) {
response.error("An error has occurred")
});
});
And an errror is being thrown of type
TypeError: Cannot call method 'add' of undefined at main.js:10:11
I am relatively new to javascript so any advice would be great. Also the relation friendRequests exists already.
This should work.
Parse.Cloud.define('addFriendRequest', function(request, response) {
Parse.Cloud.useMasterKey();
var userObjectId = request.params.userObjectId;
var user = Parse.User.createWithoutData(userObjectId);
var relation = user.relation('friendRelation');
relation.add(request.user);
user.save().then(function(user) {
response.success("Successfully added friend Request");
}, function(error) {
response.error("An error has occurred")
});
});
Some clarification of what is going on here and why your code did not work.
First of all, it is a good practice to put Parse.Cloud.useMasterKey(); right in the beginning of the function.
I see that you have the objectId of user in the beginning and that you would like to use the user based on its objectId. I order to do that, you should use Parse.User.createWithoutData('yourObjectIdHere') method. What you are actually doing for this step, is that you are creating a new user, rather then creating a reference for the one you already have in the database.
If you want to get a relation of a particular object (User object in your case) your use Parse.Object.relation('putRelationKeyHere'). You are actually creating a new relation instead of accessing the existing one.
I would recommend you to read Parse Javascript Guide in order to learn the recommended techniques.

Parse.com security Role not saving

This is my first time playing around with security roles in Parse and I believe what I'm trying to do is fairly simple. I want to create a new security Role after I signup a new user using the afterSave trigger in CloudCode.
I've verified that this is being called and the roleName is correct, but nothing is being saved in the data browser. I feel like I'm missing something pretty basic here for this not to be working - is there a setting somewhere I need to turn on?
Parse.Cloud.afterSave(Parse.User, function(request, response) {
var user = request.object;
if (user.existed()) { return; }
var acl = new Parse.ACL();
acl.setPublicReadAccess(false);
acl.setPublicWriteAccess(false);
var roleName = user.get("email");
Parse.Cloud.useMasterKey();
var companyRole = new Parse.Role(roleName, acl);
console.log("Role = " + companyRole);
companyRole.save();
});
Found the solution. In Parse, you the name for a Role can only contains letters, numbers, and underscore. I was trying to set the role name as an email address, which contains '#' and '.'
I did a replace on these characters before I saved the name and worked perfectly. I wish Parse would've thrown an error if trying to save with invalid characters but problem solved now.

Need to run code on save and log from Parse Cloud Code when updating PFObject's key in iOS app

I have a PFObject that has an array key. I can successfully call addObject: on this PFObject, and can confirm that the object has been added to the array key properly using an NSLog. However, when I try to save the PFObject to Parse, even though it says everything went successful, the changes are not shown in the Data Browser.
I have tried everything, and can even get this to work in an older version of my app, but for some reason it will not work anymore.
I posted another StackOverflow question about this here
The only response I got were some comments saying that I should trigger a "before save" function and log everything via Cloud Code. The problem is I don't know javascript, and I've been messing around with Cloud Code and nothing's happening.
Here is the code I am executing in my app:
[self.message addObject:currentUsersObjectId forKey:#"myArrayKey"];
And then I am using saveInBackgroundWithBlock:
I need to alter Cloud Code so that it will check the self.message object's "myArrayKey" before saving and log the results.
Edit 2:
Here is how I create currentUsersObjectId:
NSString *currentUsersObjectId = [[NSString alloc]init];
PFUser *user = [PFUser currentUser];
currentUsersObjectId = user.objectId;
Edit 3:
Here is the save block
[self.message saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
NSLog(#"An error has occurred.");
}
}];
Edit 4:
After adding Timothy's cloud code, the saveInBackgroundWithBlock: now does not successfully complete. Instead an error occurs, and the error object NSLogs as `"Error: Uncaught Tried to save an object with a pointer to a new, unsaved object. (Code: 141, Version: 1.2.17)" and also as:
Error Domain=Parse Code=141 "The operation couldn’t be completed. (Parse error 141.)" UserInfo=0x15dc4550 {code=141, error=Uncaught Tried to save an object with a pointer to a new, unsaved object.} {
code = 141;
error = "Uncaught Tried to save an object with a pointer to a new, unsaved object.";
}
Here is my complete Cloud Code file after adding Timothy's code:
Parse.Cloud.define('editUser', function(request, response) {
var userId = request.params.userId;
//newColText = request.params.newColText;
var User = Parse.Object.extend('_User'),
user = new User({ objectId: userId });
var currentUser = request.user;
var relation = user.relation("friendsRelation");
relation.add(currentUser);
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
});
Parse.Cloud.beforeSave("Messages", function(request, response) {
var message = request.object;
// output just the ID so we can check it in the Data Browser
console.log("Saving message with ID:", message.id);
// output the whole object so we can see all the details including "didRespond"
console.log(message);
response.success();
});
// log the after-save too, to confirm it was saved
Parse.Cloud.afterSave("Messages", function(request, response) {
var message = request.object;
// output just the ID so we can check it in the Data Browser
console.log("Saved message with ID:", message.id);
// output the whole object so we can see all the details including "didRespond"
console.log(message);
response.success();
});
After much back and forth, I'm stumped as to why this isn't working for you. As for logging in Cloud Code, if you follow the guide on adding code you can add the following to your main.js and deploy it:
Parse.Cloud.beforeSave("Messages", function(request, response) {
var message = request.object;
// output just the ID so we can check it in the Data Browser
console.log("Saving message with ID:", message.id);
// output the whole object so we can see all the details including "didRespond"
console.log(message);
response.success();
});
// log the after-save too, to confirm it was saved
Parse.Cloud.afterSave("Messages", function(request, response) {
var message = request.object;
// output just the ID so we can check it in the Data Browser
console.log("Saved message with ID:", message.id);
// output the whole object so we can see all the details including "didRespond"
console.log(message);
response.success();
});
With those in place you have plenty of server-side logging that you can check.
I am adding my own answer in addition to Timothy's in case anyone else is having a problem similar to this. My app uses the following library to allow parse objects to be stored using NSUserDefaults: https://github.com/eladb/Parse-NSCoding
For whatever reason, after unarchiving the parse objects, they are not able to be saved properly to the Parse database. I had to query the database using the unarchived one's objectId and retrieve a fresh version of the object, and then I was able to successfully make changes to and save the retrieved object.
I have no idea why this is happening now. I have never had any problems until about two weeks ago when I tried to deploy a new version of my cloud code, and if I remember correctly, Parse wanted me to update the Parse SDK or the Cloud Code version before I could deploy it.
These changes must not be compatible with these categories.

Unable to update each column of Parse Object

I am updating an object. I first find it by doing the following:
**EDIT**
Additional code added for setting and saving the object.
var query = new Parse.Query(iBeacon);
query.equalTo("uuid", searchUUID.children("input[type=text]").val().toString());
query.find({
success: function(results) {
var detailsObject = results[0];
//tduuid, tdoffer, tdproximity etc are globals intitialized earlier in code
//from values obtained from html table cells
var uuid = tduuid.children("input[type=text]").val().toString();
var offer = tdoffer.children("input[type=text]").val().toString();
var prox = parseInt(tdproximity.children("input[type=text]").val().toString());
var campaignId =tdcampaignId.children("input[type=text]").val().toString();
var location = tdGeoLocation.children("input[type=text]").val().toString();
var subLoc = tdinStoreLocation.children("input[type=text]").val().toString();
detailsObject.set("proximity", prox);
detailsObject.set("campaignId", campaignId);
detailsObject.set("location", location);
detailsObject.set("sub_location", subLoc);
detailsObject.set("uuid", uuid);
detailsObject.save(null, {
success: function(detailsObject) {
var content = Parse.Object.extend("Content");
var contentQuery = new Parse.Query(content);
var id = detailsObject.id;
//Querying Content Table on detailsObject to obtain correct record
contentQuery.equalTo("descId", detailsObject);
contentQuery.find({
success:function(contentObject){
contentObject[0].set("offer", offer);
contentObject[0].save(null, {
success: function (result){
//alert("offer saved successfully");
document.location.reload(true);
}, error:function(error){
alert("unable to save offer");
}
});
},error: function(error){
alert("Error "+ error.message);
}
});
},
error: function(error) {
alert(error.code + " , " + error.message);
}
});
},
error: function(error) {
alert(error.message);
}
});
So you can see I queried the column "uuid" in the iBeacon class. I am updating based on data entered into an html table by the user. I can update every other column but I can't update my "uuid", I am guessing that as this is part of the query I can't do it this way? I have tried this by finding the object with different parameters and it's that in particular that can't be updated....I need to update this and I'd appreciate any help on it.
FURTHER EDIT
I have been trying out things on this and have since noticed that if I put a hard coded string into where I set the uuid i.e. detailsObject.set("uuid", "UUID EDIT"); this works correctly, however, when I set uuid with the value obtained from the table cell is doesn't proceed. I have debugged it and the correct values are obtained. For testing, I queried the categoryId, when I tried to update the categoryId it wouldn't work either, but if I updated the uuid or any other columns without updating the categoryId, there was no problem.
Using a different editor I get an uncaught TypeError when debugging Uncaught TypeError: Cannot read property 'set' of undefined
One thing to be aware of is that Parse strings are case sensitive. If you store them as lower-case, you need to search using lower-case.
With something like your uuid field you can force the input to lower/upper case before writing it, and then also force user input used for search to lower/upper case as needed.
I have finally solved this myself. This issue was indeed that when searching the query was taking in the edited uuid and not the original uuid, there was a mix up with initialisation with javascript.
So I needed to store the original uuid(which was pulled from parse) as a global string variable. I had stored it incorrectly.
Thank you everyone for your help

Using CloudCode to add data to existing attribute causes error

For each User object, I have an attribute called "trueFriends" where it contains an array of userIds. I would like to modify an user's list of "trueFriends" every time a friend is added, and am using the following Cloud Code function:
Parse.Cloud.define('editUser', function(request, response) {
var userId = request.params.userId,
trueFriends = request.params.trueFriends;
var User = Parse.Object.extend('_User'),
user = new User({ objectId: userId });
user.add('trueFriends', trueFriends); //<-- If I change to "true_friends", this code works
Parse.Cloud.useMasterKey();
user.save().then(function(user) {
response.success(user);
}, function(error) {
response.error(error)
});
});
I then call the function normally from my iOS app:
[PFCloud callFunctionInBackground:#"editUser" withParameters:
#{#"userId": userToAdd.objectId,
#"trueFriends": self.currentUser.username}
block:^(id object, NSError *error) {
}];
However, I get the error "Uncaught Tried to save an object with a pointer to a new, unsaved object." As per the comment in the Cloud code, if I change the code from "trueFriends" to "true_friends", it then no longer gives this error and everything saves successfully. I am unsure how to resolve the situation, despite looking at similar questions - thanks for the help!

Categories