Ramon
Ramon

Reputation: 121

How to ensure unique key while using Parse database

I need unique records my Parse object but due to the 'saveinbackground' a simple find() on the client didn't do the job. Even adding and setting a boolean like bSavingInbackGround and skip an additional save if true wouldn't prevent my app from creating duplicates.

Ensure unique keys is obvious very helpfull in many (multi user) situations.

Parse CloudCode would be the right way but I didn't find a proper solution.

Upvotes: 0

Views: 958

Answers (2)

user922707
user922707

Reputation:

Your approach is the correct approach, but from a performance point of view, I think using query.first() is faster than query.count() since query.first() will stop as soon as it finds a matching record, whereas query.count() will have to go through the whole class records to return matching the number of matching records, this can be costly if you have a huge class.

Upvotes: 1

Ramon
Ramon

Reputation: 121

After doing some trail and error testing I finally got it to work using Cloud Code. Hope it helps someone else.

My 'table' is myObjectClass and the field that needs to be unique is 'myKey'. Add this to main.js an upload to Parse Server Cloud Code. Change myObjectClass and 'myKey' to suit your needs:

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();
}  
});

Upvotes: 1

Related Questions