Tag Archives: Cloud Code

How make row in Parse Unique using Parse CloudCode

In the Parse app database there is no option to make a key (object) unique. Usually you can chat using af find before adding a row but when you use .saveinbackground()  you cannot be sure.

Best solution is to add a beforeSave trigger on Parse Server using cloud code. I’m not a cloud code specialist so it took me quite a while to figure it out but using the code below you should be able to do this pretty quick.

This needs no modification of you app.

Add this (and adust to your needs) to you main.js and upload to Parse Server.

myObjectClass is the ‘table name’ in Parse.
myKey is the ‘field’ you want to make unique within your table (object)

Parse.Cloud.beforeSave("myObjectClass", function(request, response) {
    var myObject = request.object;
    
	if (myObject.isNew()){  // only check new records, else its a update
		var query = new Parse.Query("myObjectClass");
		query.equalTo("myKey",myObject.get("myKey"));
		query.count({
			success:function(number){ //record found, don't save
				//sResult = number;
				if (number > 0 ){
					response.error("Record already exists");
				} else {
					response.success();
				}
			},
			error:function(error){ // no record found -> save
				response.success();
			}
		})
    } else {
        response.success();
    }
});