在beforeSave
挂钩中,我希望在更新之前获取对象的状态。在这种特殊情况下,它是阻止用户在完成选择后改变他们的选择。伪代码看起来像:
If (user has already voted) {
deny;
} else {
accept;
}
到目前为止我的代码是:
Parse.Cloud.beforeSave('votes', function(request, response) {
if (!request.object.isNew()) {
// This is an update. See if the user already voted
if (request.object.get('choice') !== null) {
response.error('Not allowed to change your choice once submitted');
}
}
response.success();
}
但request.object
是已应用更新的对象的状态。
请注意,'votes'对象是单独创建的,因此不允许插入但不允许更新是不够的;我需要知道数据库中是否已经设置了一个给定的字段。
答案 0 :(得分:15)
虽然Krodmannix的回答是正确的(并且对我有帮助),但它有完整查询的开销。如果你在beforeSave中做事,你真的想简化它们。因此,我相信fetch命令是更可取的。
Parse.Cloud.beforeSave('votes', function(request, response) {
if (!request.object.isNew()) {
var Votes = Parse.Object.extend("votes");
var oldVote = new Votes();
oldVote.set("objectId",request.object.id);
oldVote.fetch({
success: function(oldVote) {
if (oldVote('choice') !== null) {
response.error('Not allowed to change your choice once submitted');
}
else {
response.success(); // Only after we check for error do we call success
}
},
error: function(oldVote, error) {
response.error(error.message);
}
});
});
答案 1 :(得分:9)
您可以使用Parse DirtyKeys来识别哪个字段已更改。
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
for (dirtyKey in request.object.dirtyKeys()) {
if (dirtyKey === "yourfieldname") {
response.error("User is not allowed to modify " + dirtyKey);
return;
}
}
response.success();
});
答案 2 :(得分:8)
request
变量是更新的行本身。您可以通过request.object.id
获取它的对象ID,并使用它从数据库中获取当前行并检查当前值,如下所示:
Parse.Cloud.beforeSave('votes', function(request, response) {
if (!request.object.isNew()) {
var query = new Parse.Query("votes");
query.get(request.object.id, { // Gets row you're trying to update
success: function(row) {
if (row.get('choice') !== null)
response.error('Not allowed to change your choice once submitted');
response.success(); // Only after we check for error do we call success
},
error: function(row, error) {
response.error(error.message);
}
});
}
答案 3 :(得分:7)
如果您使用的是自托管的Parse Server,则会根据请求提供一个名为" original"这是改变前的对象。
Parse.Cloud.beforeSave("Post", function(request, response) {
console.log(request.object); //contains changes
console.log(request.original); //contains original
response.success();
});
答案 4 :(得分:0)
这项工作:
var dirtyKeys = request.object.dirtyKeys();
var query = new Parse.Query("Question");
var clonedData = null;
query.equalTo("objectId", request.object.id);
query.find().then(function(data){
var clonedPatch = request.object.toJSON();
clonedData = data[0];
clonedData = clonedData.toJSON();
console.log("this is the data : ", clonedData, clonedPatch, dirtyKeys);
response.success();
}).then(null, function(err){
console.log("the error is : ", err);
});