I have objects in Parse called "Post" and within that, I have columns called "title" and "content". I am trying to ask the user for an input value and save this as "remove". If the user's input value ("remove") matches a "title" value already saved in parse.com, I want to delete the entire row in parse, so that both the "title", "content" and everything else in the row is deleted. The deleting part is not working so I am wondering if my code is actually making it go through all the data saved in parse and find the one that matches the user's input and then delete it.
What am I doing incorrectly and what can I change to make it delete the entire row?
Thank you in advance.
function getPosts(){
var query = new Parse.Query(Post);
query.find({
success: function(results){
for(var i in results){
var title = results[i].get("title");
var content = results[i].get("content");
var remove = $("#post-remove").val();
console.log("Remove: "+remove);
console.log("MAC Address: " +title);
console.log("place: "+content);
if (title == remove)
{
window.alert("The MAC address matches.");
console.log(remove+" matches " + title+ " and is located in " +content);
var Post = Parse.Object.extend("Post");
var query = new Parse.Query(Post);
query.find("objectId", {
success: function(yourObj){
//console.log(yourObj);
//Post.destroy({}); //if title matches remove, delete the Post (title and content) (but it's not deleting it)
Post.remove("title");
Post.remove("content");
}
});
}
}
}
});
}
To clarify and add a bit to #JakeT's acceptable answer:
1) find objects to delete like this:
function postsMatching(title) {
var Post = Parse.Object.extend("Post");
var query = new Parse.Query(Post);
query.equalTo("title", title);
return query.find();
}
2) Delete an array of parse objects like this:
Parse.Object.destroyAll(posts);
3) Put the two ideas together (returning a promise to find then delete) like this:
var title = $("#post-remove").val();
postsMatching(title).then(function(posts) {
console.log("deleting " + JSON.stringify(posts));
Parse.Object.destroyAll(posts);
}, function(error) {
console.log("error " + JSON.stringify(error));
});
First of, you can use the Parse.Query.equalTo(key, value) method to filter for the Post/s you are looking for. That will render a lot of your logic unnecessary.
Additionally, since most parse calls are asynchronous, I would suggest learning about Parse Promises and using those instead of the call backs you're using.
Finally, you don't need a second nested query, since you already have the object you are trying to destroy. You just need to call destroy() on that object, and if you have some extra content you need to take care of deleting (i.e., your 'content' is a pointer to another object that is owned only by the Post you are deleting), you should set up a beforeDestroy() trigger for the Post object in your cloud code that will delete that pointer as well.
Related
Context
In a Firebase DB I'm storing "events" and "users". Users can have favorite events, to manage them I only store the event's id in the favorite user's DB location. So to grab favorite events informations, I need to firstable grab the event id and then go to the DB events location, to collect all the datas I need.
Problem
I would like to store in an Array all the favorite events informations (each event would be an Object with inside it : "key" : "value"), to use that Array in my HTML view and print the informations. But it doesn't work the way I coded it... :(
// This ref is too grab favorite event id (in my case only 2) in the user DB location
var refUserFavoris = firebase.database().ref().child("users/"+user.uid+"/events/favoris");
$scope.favorisTmp = $firebaseArray(refUserFavoris);
// This shows one array, with two objects (wich are my two user's favorite events) wich include ids
console.log($scope.favorisTmp);
// This is to load the objects and with the foreEach, grab there ids to use them in the next ref call
$scope.favorisTmp.$loaded().then(function()
{
angular.forEach($scope.favorisTmp, function(favoris)
{
// This shows two lines : the id of each object
console.log(favoris.$id);
// Call a new ref to reach the event informations (in a different location of the DB) using the previous id
firebase.database().ref("events/"+favoris.$id).once('value').then(function(snapshot)
{
// Attempt to store events datas for each id I have (in my case, only two)
snapshot.forEach(function(favorisSnap)
{
var favSnap = favorisSnap.val();
// This shows a lot of "undefined" lines, wich I don't want. I would like two objects, with all informations inside
console.log(favSnap.nbPersonne);
// $scope.favorisF is an Array that I would like to use in a ng-repeat to print all datas for each event
// For now this doesn't show anything
$scope.favorisF = favSnap;
});
// If using favSnap out of the previous function, I got a "favSnap" is undifined error
console.log(favSnap);
});
});
});
<ion-item ng-repeat="f in favorisF" class="item-avatar">
{{f.nbPersonne}}
</ion-item>
EDIT 1 :
I tried a new way to have my data, but a new problem came, how to fill an Array inside a loop ? I've tried "push" and "$add" methods, but no one worked. Any ideas ?
var newFav = [];
var user;
user = firebase.auth().currentUser;
var refUserFavoris = firebase.database().ref().child("users/"+user.uid+"/events/favoris");
$scope.favorisTmp = $firebaseArray(refUserFavoris);
$scope.favorisTmp.$loaded().then(function()
{
angular.forEach($scope.favorisTmp, function(favoris)
{
console.log(favoris.$id);
var refFavoris = firebase.database().ref("events/"+favoris.$id);
refFavoris.on('value', function(snap)
{
//This is where I'm trying to fill "newFav" in each steps of the loop
newFav.push(snap.val());
console.log("Scope newFav vaut :", $scope.newFav);
});
});
});
I think you made a typo here.
var refUserFavoris = firebase.database().ref("events/favoris/"+favoris.$id).once('value')
Thanks a lot Abdel, I fixed my problem :
Here is the solution
$scope.newFav = [];
console.log($scope.newFav);
$scope.favorisTmp.$loaded().then(function()
{
angular.forEach($scope.favorisTmp, function(favoris)
{
console.log(favoris.$id);
var refFavoris = firebase.database().ref("events/"+favoris.$id);
refFavoris.on('value', function(snap)
{
$scope.newFav.push(snap.val());
console.log("Scope newFav vaut :", $scope.newFav);
});
});
});
Here is the problematic code:
let newFriend = event.target.id;
let friends;
if (sessionStorage.getItem('friends') === null || sessionStorage.getItem('friends') === undefined || sessionStorage.getItem('friends') === '') {
console.log('DEV_NO FRIENDS!sessionStorage[\'friends\']: ' + sessionStorage.getItem('friends'));
friends = [newFriend];
} else {
let currentFriends = sessionStorage.getItem('friends').split(',');
console.log(currentFriends.length);
// let currentFriends = JSON.parse(sessionStorage.getItem('friends'));
console.log('DEV_sessionStorage friends: ' + currentFriends);
console.log('DEV_inArray condition: ' + $.inArray(newFriend, currentFriends));
if (!($.inArray(newFriend, currentFriends) !== -1)) {
console.log('DEV_if not in array!');
friends = currentFriends.push(newFriend);
console.log('DEV_friends in if: ' + friends);
}
}
let data = {friends: friends};
It is hooked on image tag. The sessionStorage fills on successful login like so:
if (response['friends'] !== undefined) {
sessionStorage.setItem('friends', response['friends']);
} else {
sessionStorage.removeItem('friends');
}
Or is updated like so, if new friend is added:
ajax(url, 'GET', 'none', 'Kinvey', function(response) {
sessionStorage.setItem('friends', response['friends']);
});
The idea is: a user can add friends to his friends list. The friend is 'PUT' into my app's back-end, inside a column called 'friends'. Then sessionStorage is updated to store the new friend. To my knowledge sessionStorage supports only strings, so I thought lets store the friends as string, separated by ",". Then I would pick that up ('currentFriends') and split that string into array. Then push the next item and send the data back to the server, then update sessionStorage. But I simply cannot do it - I've been trying for over 3 hours now. As you can see with the numerous console.log()s, for some reason I cannot process my data accordingly and I have no idea what am I doing wrong. Sorry for the long post, but I'm really stuck in here..
Bottom line: as #dfasoro kindly explained - when working with REST one should always make sure he keeps his data in JSON strings. My second problem was that array.push() returns integer (length of array) instead of new array.
I hope this will help you, I have helped you refactor your code and removed unneccesaries, I hope the inline comments help you as well.
IMAGE HOOK CODE
let newFriend = event.target.id;
let friends = [];
if (sessionStorage.getItem('friends')) {
try {
//this will throw an error if invalid array json is in friends sessionStorage
friends = JSON.parse(sessionStorage.getItem('friends'));
}
catch (e) { }
}
//is friend in the array?
//if not add and store back into sessionStorage
if (friends.indexOf(newFriend) == -1) {
friends.push(newFriend);
sessionStorage.setItem('friends', JSON.stringify(friends));
}
let data = {friends: friends};
//continue with your image hook code
LOGIN CODE
//login code
if (response['friends']) {
sessionStorage.setItem('friends', JSON.stringify(response['friends']));
} else {
sessionStorage.removeItem('friends');
}
PUT CODE
//update PUT code
ajax(url, 'GET', 'none', 'Kinvey', function(response) {
sessionStorage.setItem('friends', JSON.stringify(response['friends']));
});
You basically store the data as JSON string and retrieve as JSON object. You also don't need the null, undefined, empty test etc. You are basically trying to test for a falsy value.
I also really hope that your response object is a standard JSON object mapped to a friend array and not a comma separated list of friends e.g.
{"friends": [4, 5, 3, 2]} and not `{"friends": "4, 5, 3, 2"}"
The above works perfect as sessionStorage only uses a key value pair.
Though I also use sessionJS to get/set/delete data to/from sessionStorage
maybe this will also help you.
I'm using the Parse.com javascript SDK and I'm trying to set some fields of the object in the loop, but only those fields which I am creating in the loop are not getting saved in parse also it is not giving me any error.
CODE:
var room = new Room();
room.id = params.roomId;
var rate = new Rate();
rate.set('room', room);
for (var i = 0; i < 100; i++) {
rate.set("rate" + i, params.price); // this fields are not getting saved
}
rate.save(null, {
success: function(rate) {
params.success(Response.SaveSuccess);
},
error: function(rate, error) {
console.log('ERROR SAVING RATE: ' + error.message);
params.error(Response.InternalServerError);
}
});
After successful response, I can see only room field in database
The way you are trying to set values in rate object seems a little weird. The first argument of "set" method of Parse.Object accepts only column name enclosed in inverted commas. So following is the only solution of updating an object in Parse Js:
rate.set("rate", params.price);
P.S. You need to elaborate what exactly you want to achieve in your code so that a proper solution can be posted.
Thanks
so I have a JSON object returned from a webservice. Now I want to:
get a subset which matches a categoryTitle i pass as parameter (this seems to work)
from my filtered resultset I want to get another array of objects (helpsubjects), and for each of this subjects I want to extract the SubjectTitle.
Problem: It seems my Array of HelpSubjects does not exist, but I can't figure out why and hope you could help.
Perhaps this piece of commented code makes it more clear:
$.fn.helpTopicMenu = function (data) {
that = this;
var categoryContent = contents.filter(function (el) {
return el.CategoryTitle == data.categoryTitle;
});
debug('categorys Content: ', categoryContent); //see below
var container = $('#subjectList');
var subjectList = categoryContent.HelpSubjects;
debug('Subjects in Category: ', subjectList); // UNDEFINED?!
$.each(subjectList, function (i, item) {
container.append(
$('<li></li>').html(subjectList[i].SubjectTitle)
);
});
the line debug('categorys Content: ', categoryContent); returns the following object as shown in the picutre (sadly I can't add a picture directly to the post yet, so here's the link): http://i.stack.imgur.com/0kKWx.png
so as I understand it, there IS actually a HelpSubjects-Array, each entry containing a SubjectTitle (in the picture there actually is only one entry, but I need to have the Artikel einfügen as my html.
Would be great if you can help me.
The variable categoryContent set is an array of objects.
Try debugging categoryContent[0].HelpSubjects and see if you can access the property. If so, you can also loop this array if need be.
I'm trying to check if I have something in an array already before adding - so that I cannot add the same type more than once. I am checking the model of the drop down I am selecting from against the array I am storing everything in (there is a slight difference in that the model stores the id as id and the array as skillId).
I am basically just trying to look through the array and see if the id matches - and if it does do not add the item to the array. Here is the code.
$scope.saveSkill = function() {
//send skill to get path, then add to skills array
console.log($scope.pathArray);
console.log($scope.scope5.id);
var skillCheck = true;
//check if exists aready
for(i=0;i<$scope.pathArray.length;i++){
if($scope.pathArray[i].skillId = $scope.scope5.id ){
console.log("Cannot add same skill more than once");
skillCheck = false;
}
}
if(skillCheck){
$http({
method: 'GET',
url: '/findPathScopeToSkill/' + $scope.scope5.id + "/1"
})
.success(function(data){
angular.forEach(data.paths, function(index) {
$scope.pathArray.push(index);
});
});
}
};
Just as a quick reference - pathArray is where the items get pushed into and where I do not want to have doubles - so I am checking the current id vs the id's inside the array (only difference is they are .skillId's)
I can add one, then can't add the same one again BUT I also can't add any after that. Can't seem to figure out what I am doing wrong here. Any help would be greatly appreciated. Thanks!