更新对象或创建对象(如果不存在)

Update Object or Create it if it doesn't exists?

本文关键字:如果不 不存在 如果 对象 创建对象 更新      更新时间:2023-09-26

我正在挖掘一些云代码来对数据进行一些操作并将其另存为新类。

遇到这样一种情况:我从另一个类读取一行,执行一些数学函数,然后将操作的数据保存到另一个类,然后由我们的客户读取。

问题是,如果新类中已经存在另一个对象,我只想更新它而不是创建一个新对象。 我知道在解析文档中它列出了创建对象和更新,但不是真正的更新功能(如果存在),如果没有创建。

这里只是一些示例代码.. out 数据是为新类准备保存的数据。 我可以创建新的类对象,但是当我更新一些值时应该触发更新而不是创建新的是事情分崩离析的地方。

请理解JS不是我的第一语言,所以这可能会被黑客入侵或完全以错误的方式进行,但我应该强调我不知道的对象ID新类。

if(out.length > 0) {   
  var game = Parse.Object.extend("Gamers");
  var query = new Parse.Query(game);
  query.equalTo("playername", player);  // using this to find the player since I dont have the objectid
  query.find({                       
    success: function(results) {
    // Successfully retrieved the object.
    if (results && results.length == "1") {
      var playerObjectId = results[0].id
      /// save only updated data to the local class ????
    } else {
      // no results, create a new local
      console.log('no results')
      // save as a new object
      var gamers = new game();
      gamers.set("somevalue", somevalue);
      gamers.set("somevalue2", somevalue2);
      gamers.save(null, {
        success: function(gamers) {
          // Execute any logic that should take place after the object is saved.
          console.log('New object created with objectId: ' + gamers.id);
        },
        error: function(gamers, error) {
          // Execute any logic that should take place if the save fails.
          // error is a Parse.Error with an error code and message.
          console.log('Failed to create new object, with error code: ' + error.message);
        }
      });                    
    }
  },
  error: function(error) {
    console.log("Error: " + error.code + " " + error.message);
  }
});
} else {
console.log('array is empty, something went wrong')
 //this array is empty
}

创建或更新函数有三个不同的位:查找、更新或可能创建。 让我们分别构建这三个。

function findGamerWithName(name) {
    var game = Parse.Object.extend("Gamers");
    query.equalTo("playername", name);
    return query.find();
}
function updateGamer(gamer, someValue, someValue2) {
    gamer.set("somevalue", someValue);
    gamer.set("somevalue2", someValue2);
    return gamer.save();
}     
function createGamer(someValue, someValue2) {
    var Gamer = Parse.Object.extend("Gamers");
    var gamer = new Gamer();
    return updateGamer(gamer, someValue, someValue2); 
}

现在我们可以分别理解和测试它们(您应该测试它们)。 现在,编写创建或更新逻辑很容易...

function createOrUpdateGamer(name, someValue, someValue2) {
    return findGamerWithName(name).then(function(gamer) {
        return (gamer)? updateGamer(gamer, someValue, someValue2) : createGamer(someValue, someValue2);
    });
}