Sapan Diwakar

Software developer

Follow me on Twitter Check out my code on GitHub View some of my designs on Dribbble Take a look at my Linked In profile

Uniqueness constraints in Parse Database

Parse is a great service for quickly getting an app out without getting into too much backend/server/database details. Its really easy to quickly set up your database schema and start saving and querying data. However, one of the most important things that it currently misses is the ability to provide constraints on the data. There is no way to say, for example, that two users cannot have the same email addresses.

The best way to impose constraints on data is to use Cloud Code beforeSave hook to validate the data before it is inserted in the database. Cloud code is really easy to set up and get started with.

Let's see how we can add a simple uniqueness constraint for the database such that a user cannot register a like for a post twice. We have a PostLike that stores post, user pairs for each like. To ensure that a user cannot like the same post twice, before saving each like, we check if the post, user pair already exists and discard the like if it does.

// Prevent duplicate (post, user) pairs for likes
Parse.Cloud.beforeSave("PostLike", function(request, response) {  
  var query = new Parse.Query("PostLike");
  query.equalTo("post", request.object.get("post"));
  query.equalTo("user", request.object.get("user"));
  query.find({
    success: function(likes) {
      if (likes && likes.length > 0) {
        response.error("this user already likes this post");
      } else {
        response.success();
      }
    },
    error: function(error) {
      // No existing like
      response.success();
    }
  });
});