Prevent duplicate with BeforeSave but allow update of objects

Hello,

In order to prevent duplicates from being save in my community class, I created the following hook:

Moralis.Cloud.beforeSave("community", async (request) => {
  const logger = Moralis.Cloud.getLogger();
  const tokenId = request.object.get("tokenId");
  const community = Moralis.Object.extend("community");
  const query = new Moralis.Query(community);
  query.equalTo("tokenId", tokenId);
  const duplicate = await query.find();
  if (duplicate.length !== 0) {
        logger.info("This community already exist");
        throw "validation error";
      } else {
        logger.info("This community doesn't exist yet in our db");
      }
});

It works well but it also blocks me from updating an already existing object. Any idea on how I can prevent the creation of a new object that already exists while enabling the update of previously existing objects?

maybe you can check the id for the current object and the object that will be saved, if is the same id than maybe it is an update

1 Like