我使用此代码使用Parse Cloud保存数据,我有一个唯一的列“number_plate”我遇到了一个问题,那就是当我尝试更新对象时我无法这样做。
<script type="text/javascript">
$(document).ready(function() {
$('.addnewpostajax').submit(function() {
var post_text = $('.StatusText').val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url('home/AddPost'); ?>",
dataType: "json",
data: {post_text},
success: function(posted) {
if(posted == true) {
window.location.reload(true);
} else {
alert('Faild');
}
}
});
});
});
</script>
**
更新:我根据给定答案使用的新代码:
**
var Car = Parse.Object.extend("Car");
// Check if number plate is set, and enforce uniqueness based on the number plate column.
Parse.Cloud.beforeSave("Car", function(request, response) {
if (!request.object.get("number_plate")) {
response.error('The number plate was not provided.');
} else {
var query = new Parse.Query(Car);
query.equalTo("number_plate", request.object.get("number_plate"));
query.first({
success: function(object) {
if (object) {
response.error("A Car with this number plate already exists.");
} else {
response.success();
}
},
error: function(error) {
response.error("Could not validate uniqueness for this Car because the number plate is repeated.");
}
});
}
});
答案 0 :(得分:2)
这种情况下的关键是使用承诺。
您想要达到的目标如下:
Parse.Cloud.beforeSave("Car", function(request, response) {
if (!request.object.isNew()) {
// Let existing object updates go through
response.success();
}
var query = new Parse.Query("Car");
// Add query filters to check for uniqueness
query.equalTo("number_plate", request.object.get("number_plate"));
query.first().then(function(existingObject) {
if (existingObject) {
// Update existing object. here you can do all the object updates you want
if (request.object.get("columnToUpdate") != undefined){
existingObject.set('columnToUpdate',request.object.get("columnToUpdate"));
}
return existingObject.save();
response.error();
} else {
// Pass a flag that this is not an existing object
return Parse.Promise.as(false);
}
}).then(function(existingObject) {
if (existingObject) {
// Existing object, stop initial save
response.error("Existing object");
} else {
// New object, let the save go through
response.success();
}
}, function (error) {
response.error(error);
});
});