在Parse中创建OR更新对象

时间:2015-02-18 14:25:25

标签: javascript angularjs parse-platform ionic

我正在创建一个使用Parse.com作为后端的Ionic应用程序。我想将项目保存到现有的对象,但如果它已经存在,那么我想更新该项目。我已尝试使用文档中的.save,但它会不断创建新行。

我可以使用以下方法查询现有ID:

var ExisitingId = Parse.Object.extend("Exercises");
var query = new Parse.Query(ExisitingId);

query.equalTo("exerciseName", $scope.currentExcercise);
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('exerciseName already Exists'));
      var ExisitingIdNumber = object.id;
    }
  },
  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  }
});

这是我的代码,用于在对象Exercises中创建/保存行:

$scope.saveToParse = function(exercise) {

var Exercises = Parse.Object.extend("Exercises");
var exercises = new Exercises();

exercises.set({exerciseName: exercise.ExerciseName,
          exerciseID: exercise.ExerciseID,
          exerciseDescription: exercise.Description,
          sets: exercise.Sets,
          reps: exercise.Reps,
          resistance: exercise.Resistance,
          tempo: exercise.Tempo,
          images: $scope.images})

exercises.save(null, {
  success: function(exercises) {
    // Execute any logic that should take place after the object is saved.
    alert('Exercise saved with objectId: ' + exercises.id);
  },
  error: function(exercises, error) {
    // Execute any logic that should take place if the save fails.
    // error is a Parse.Error with an error code and message.
    alert('Failed to create new object, with error code: ' + error.message);
  }
});

}

理想情况下,我希望将这两个函数结合起来检查现有值,然后自动创建/更新。

关心西蒙

1 个答案:

答案 0 :(得分:1)

这很有效......

$scope.saveToParse = function(exercise) {

var Exercises = Parse.Object.extend("Exercises");
var exercises = new Exercises();
exercises.id = $scope.ExisitingExerciseID;
console.log($scope.ExisitingExerciseID);

exercises.fetch()
.then(function(){
      exercises.set({exerciseName: exercise.ExerciseName,
          exerciseID: exercise.ExerciseID,
          exerciseDescription: exercise.Description,
          sets: exercise.Sets,
          reps: exercise.Reps,
          resistance: exercise.Resistance,
          tempo: exercise.Tempo,
          images: $scope.images})

      return exercises.save();
       $state.go('app.exercises', {clear: true});

})
}