Created
January 4, 2016 01:05
-
-
Save kevinzhang96/1d4680b953e33342f6ab to your computer and use it in GitHub Desktop.
Upsert Parse Cloud
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Takes 3 parameters: | |
// class: the object type to update; a single String. | |
// restrictions: the set of column restrictions; a Dictionary. | |
// updates: the set of column updates; a Dictionary. | |
Parse.Cloud.define("upsert", function(request, response) { | |
var query = new Parse.Query(request.params.class); | |
var restrictions = JSON.parse(request.params.restrictions); | |
for (var key in restrictions) { | |
query.equalTo(key, restrictions[key]); | |
} | |
query.find().then(function(results) { | |
var updates = JSON.parse(request.params.updates); | |
if (results.length > 0) { | |
for (var i = 0; i < results.length; i++) { | |
for (var key in updates) { | |
results[i].set(key, updates[key]); | |
} | |
} | |
Parse.Object.saveAll(results).then(function(results){ | |
response.success(results.length + " object(s) were updated!"); | |
},function(error){ | |
response.error(error); | |
}); | |
} else { | |
var objectClass = Parse.Object.extend(request.params.class); | |
var object = new objectClass(); | |
for (var key in updates) { | |
object.set(key, updates[key]); | |
} | |
object.save(null, { | |
success: function(obj) { | |
response.success("1 new object was inserted!"); | |
}, | |
error: function(error) { | |
response.error(error); | |
} | |
}); | |
} | |
}, function(error) { | |
response.error(error); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is just what I was looking for. Any problems with it? Is this still the best way to do an upset.
Thanks big time!