Updating a specific record in the database?

681 Views Asked by At

I'm using Javascript with applab. The code creates new users fine, but it only updates the first record. Any ideas how to fix this so that it will update for each new and returning user? I think I need to use a math function with "mostRecentID" or "record.ID" to achieve this. Link to Project: https://studio.code.org/projects/applab/bSkJw2auZx8Iq7ZGemsT7HwQrOVBWFPl6eLl0R0a6VU If you go to "how it works (view code)", and then you can see the code and the database.

//The database for this code already exists.
//This code creates new users fine, but it only updates the first record.
//What code will update a specific ID in the database 
//I think I need to use a math function with "mostRecentID" or  "record.ID" to achieve this.
var mostRecentID=1;
var player = {};
var UserID = getUserId();
onEvent("addNewRecordButton", "click", function() {
  readRecords("AllUserData", player, function(records) {
      var count = records.length;
      if (count > 1) {
          
      } else if ((count == 1)) {
          
      } else {
          var player = {};
          player.UserID = getUserId();
          player.Username=getText("usernameInput");
          createRecord("AllUserData", player, function(record) {
              mostRecentID=record.id;
          });
      }
  });
});
onEvent("updateInformationButton", "click", function() {
  updateRecord("AllUserData", {id:mostRecentID,UserID:getUserId(),Username:(getText("usernameInput"))}, function() {
    
  });
});
1

There are 1 best solutions below

0
On

Let's say you wanted to update a record matching the current user's user ID. You would need to specify the user ID in the parameters object.

readRecords("AllUserData", {UserID: getUserId()}, function (records) {
  if (records.length > 0) {
    updateRecord("AllUserData", {id: records[0].id, UserID:getUserId(),Username:(getText("usernameInput"))}, function () {
      // callback code
    });
  } else {
    createRecord("AllUserData", {UserID:getUserId(),Username:(getText("usernameInput"))}, function () {
      // callback code
    });
  }
});