[SOLVED] Save creates 2 separate rows in DB

I swear this was working correctly yesterday, I dont know what I did. When I try to create a new row, two get saved to the DB. Trying to update an existing row only changes one of them.

Can anyone see what I did wrong?

const User = Moralis.Object.extend("ZZDemoTable");
  const UserQuery = new Moralis.Query(User);
  UserQuery.equalTo("email", email);

  UserQuery.first()
    .then(async function (UserResult) {
      if (UserResult) {
        return UserResult.fetch();
      } else {
        const newUser = new User();
        newUser.set("email", email);
        newUser.set("minecraftName", MinecraftName);
        newUser.set("steamID", parseInt(SteamID));
        newUser.set("isActive", active);
        newUser.set("Tier", parseInt(Tier));
        newUser.save();
      }
    })
    .then(async function (Result) {
      if (Result) {
        Result.set("email", email);
        Result.set("minecraftName", MinecraftName);
        Result.set("steamID", parseInt(SteamID));
        Result.set("isActive", active);
        Result.set("Tier", parseInt(Tier));
        Result.save();
      }
    });

Your both .then function will run until there is an error or break statement the previous .then function.

You can change your code like this

UserQuery.first()
    .then(async function (UserResult) {
      if (UserResult) {
        let Result =  UserResult.fetch();
        Result.set("email", email);
        Result.set("minecraftName", MinecraftName);
        Result.set("steamID", parseInt(SteamID));
        Result.set("isActive", active);
        Result.set("Tier", parseInt(Tier));
        Result.save();
      } else {
        const newUser = new User();
        newUser.set("email", email);
        newUser.set("minecraftName", MinecraftName);
        newUser.set("steamID", parseInt(SteamID));
        newUser.set("isActive", active);
        newUser.set("Tier", parseInt(Tier));
        newUser.save();
      }
    })
1 Like

This did not work. I think maybe its not related to Moralis. The Submit event for the form might be getting triggered twice. I’ll have to look into that

EDIT: Yes, this is the issue. I was able to prevent the second save by clearing the form on submit. It triggers an error since one of the fields is required, but it works for now.