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
Related
I'm working on a section of my app where a user can add a note to his project. Each note has the capability to have additional comments appended to it.
So far the backend is working. When calling all records at a time or one record at a time(by id) manually, be it via postman or simply adding the id number of a project(gotten from mongo) to the browser, both pull up the records as specified.
The problem starts when I try to pull this information through the front end via
$.getJSON.
Say for example that I have two projects in my app.
Project 01 has an id of "123" and has 3 comments
and
Project 02 has an id of "456" and has 10 comments
When I call all projects on the front end of the app, I see both appear, and all their comments come through ok but when I try to call, for example, project two by id, it does show but I get 10 "undefined" for all of that projects 10 comments. Same thing happens for any one record I call.
And again, this happens only when trying to call it via jquery $.getJSON because when I manually do it via postman/browser, they come through fine.
Here is some code below for when I try to find one record (not working fully).
This is the backend code:
app.get("/notesapi/:tabID", (request, response) => {
var idNum = request.params.tabID;
var newIdNumber = idNum.trim();
NotesModel.findOne({_id: newIdNumber}, (error, data)=>{
if(error){
console.log("error in finding this particular record!");
throw error;
} else {
console.log("data for this one record found YO");
response.status(200);
response.json(data);
}
});
});
And this is the front end code:
function getFreshComments(tabID){
console.log("FRONTEND -- the link is: /notesapi/" + tabID);
$.getJSON("/notesapi/456", showCommentsGotten);
function showCommentsGotten(dataFedIn){
var tabInnerComments = $("#" + tabID +" .theNote");
var output = "";
$.each(dataFedIn, (key, item)=>{
output += item.todoMessages + "<br>";
});
var normalComments = output;
var newComments = normalComments.split(",").join("<br>");
tabInnerComments.html(newComments);
}
}
As the example explained above, if I wanted to pull the 10 comments from id 456, then when I use $.getJSON("/notesapi/456", showCommentsGotten);
This returns me 10 "undefined".
When I remove the id number from the URL, then it fetches me ALL the comments for ALL the notes.
I don't get any errors anywhere. What am I missing or doing wrong?
been reading docs and other posts but I am unable to remove a node. I am attempting to select the node by a value.
var eventContactsRef = firebase.database().ref('events-contacts');
eventContactsRef.orderByChild('eventContactId').equalTo(eventContactId);
then call the remove method on the result
eventContactsRef.remove(function (error) {
console.log(error);
});
nothing happens except a null error value. I am using the latest firebase, most examples are for older versions so I am unsure if I need to get the key and then attempt to delete with that as a reference?
This is the first time using firebase so I am not sure if I have saved the data correctly. here is code to save.
var key = firebase.database().ref().child('event-contacts').push().key;
var url = firebase.database().ref('/event-contacts/' + key);
url.set(eventContacts);
and screenshot
You cannot remove a query itself. You can only remove the results that match a query.
var eventContactsRef = firebase.database().ref('events-contacts');
var query = eventContactsRef.orderByChild('eventContactId').equalTo(eventContactId);
query.on('child_added', function(snapshot) {
snapshot.ref.remove();
})
ISSUE
I have been trying to update a field (gamesArray) from the current User (Parse.User.current()), so later in another view I can see it. The problem is that when I do it, the field gets updated (I console.log() it right after the object is saved and check it on the Database UI from Parse) but when I go to the other view, in which the User is retrieved and I show the field on screen, it is not updated.
CONTEXT
My _User has an array of Games called gamesArray so I update that array just like this:
addGameToUser = function(game, userId) {
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo("objectId", userId);
userQuery.first({
success: function(user) {
// User found
},
error: function(error) {
console.log(error.message);
}
}).then(function(user) {
// If user is current user update it
if(user.id == Parse.User.current().id) {
var games = user.get('gamesArray');
games.push(game);
user.set('gamesArray', games);
user.save(null, {
success: function(user) {
console.log(user.get('gamesArray'));
},
error: function(user, error) {
console.log(error);
}
});
}
else {
// Call cloud function...
}
});
}
In this case, console.log(user.get('gamesArray')) returns the updated field. I use this function when the user creates a new game.
The problem is that in a different view, when I retrieve the user and get that field, it is not updated:
getUserGames: function() {
var games = Parse.User.current().get('gamesArray');
console.log(games);
}
Here, console.log(games) is printing the old field value. So if I had 4 games in the array, the previous function printed 5 (4 plus the created one) and this still prints 4.
I thought that maybe I was not saving the Game properly, but this is the output of the Parse's Database UI gamesArray column of the current User:
[{"__type":"Pointer","className":"Game","objectId":"..."}]
The only way that I can get the updated field is logging out and logging in with the same user.
QUESTIONS
Why is that? What am I doing wrong? How could I "update" the user so I don't have to log out?
It sounds like your user object that you are reading from is not the same specific object that you are updating. So you are updating the object in your database, but the user object you're reading from doesn't know that the object in the database has been updated. You should try fetching the user first. iOS has a fetchIfNeeded method.
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.
I have a Class in parse, say Pictures. Each of these belongs to a user. Reference to this user is stored in the Pictures table/class as a Pointer to the user.
In my cloud code I am trying to get all Pictures belonging to a user, using master key. Following is my code:
Parse.Cloud.define("getPictures", function(request, response) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query("Pictures");
query.equalTo("user", request.params.user);
query.find({
success: function(results) {
var status = "Found " + results.length + " pictures for userId " + request.params.user;
response.success(status);
},
error: function() {
status = "No pictures exist for userId " + request.params.user;
response.error(status);
}
});
});
This code outputs that there are 0 pictures for a certain user with id 'xyz' for example. However, I can see that the user has a lot of pictures stored.
I have also verified that the problem is not with using master key, as I see in the console log that the code is being executed as master. Moreover, if I query for a picture by objectId, it does come out in the results, which means ACL is not the problem here.
I think I have to use relations/joining here, but I am not sure how to do that.
Pointers are stored as objects in Parse database, so if you try to compare a string to an object with query.equalTo() function, nothing will be found. This is how pointers are stored:
{
__type: 'Pointer',
className: '_User',
objectId: user-object-id
}
If you are querying a class with pointers and want your result comes with the whole object nested, you should set this in your query:
var query = new Parse.Query('Pictures');
query.include('user');
In my queries when I want to search by a pointer column, I compare my user object with the nested user object.
var user = new Parse.User();
// Set your id to desired user object id
user.id = your-user-id;
var query = new Parse.Query('Pictures');
// This include will make your query resut comes with the full object
// instead of just a pointer
query.include('user');
// Now you'll compare your local object to database objects
query.equalTo('user', user);
query.find({
success: function(userPicture) {
response.success(userPicture);
}
});
Anyway, seems that if you have many pictures related to an user, you probably are searching for parse relations instead of pointers: https://www.parse.com/docs/relations_guide
If you write a query to retrieve a parent object and a child object to which you have pointer, but no read access as per ACL, then the query may return only parent object and child will be null because the ACL wont let you read it.
There may be a problem with your params. If "user" is a pointer, then 'request.params.user' is incorrect, because PFObjects may not be sent as params. If "user" is a pointer, use 'request.user'. If request.params.user is a string of the userId, you could use the Id to reconstruct a PFObject shell before the query as was suggested by Murilo already, but deleting the "user" param and using request.user would shorten your code and not duplicate any values. Murilo's solution is also beneficial because you could pass a userId other than the current user's Id.