Skip to content

Instantly share code, notes, and snippets.

@kevinzhang96
Created January 4, 2016 01:05
Show Gist options
  • Save kevinzhang96/1d4680b953e33342f6ab to your computer and use it in GitHub Desktop.
Save kevinzhang96/1d4680b953e33342f6ab to your computer and use it in GitHub Desktop.
Upsert Parse Cloud
// 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);
});
});
@raytrask
Copy link

raytrask commented Jul 8, 2018

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment