基本上,在我的users表中,我有一个列canHave
,它是一个对象列表Event
。所以我的Users
和Event
表
这是我的代码(云代码):
Parse.Cloud.define("updateUserCanHave", function (request, response) {
var query = new Parse.Query(Parse.User);
query.equalTo("email", request.params.mail);
query.find({
success: function (myUser) {
var newUser = myUser[0];
var myRelation = newUser.relation("canHave");
var eventsQuery = newUser.relation('canHave').query();
eventsQuery.find().then(function (events) {
myRelation.remove(events[0]);
});
newUser.save(null, {useMasterKey: true})
response.success();
}
}).catch(function (error) {
response.error("Error " + error.code + " : " + error.message + " when updating user canHave.");
});
});
但是我的用户永远不会改变,我的功能参数也很好。
答案 0 :(得分:1)
newUser.save()
将开始异步执行,然后通过同步调用response.success()
立即终止。通过保存后将响应放在执行顺序中进行修复。
我更喜欢这些调用的promise-returns表单,但如果你的样式是回调函数......
newUser.save(null, {
useMasterKey: true,
success: function(result) {
// moved here, after the save succeeds
response.success(result);
},
error: function(result, error) {
response.error(error);
}
});
编辑代码在关系查询中存在相同问题。使用回调样式方法很难清楚(甚至看到问题)。使用承诺......
function findUserByEmail(email) {
let query = new Parse.Query(Parse.User);
query.equalTo("email", email);
return query.first(); // notice "first" here, if we're going to use only the first anyway
}
Parse.Cloud.define("updateUserCanHave", function (request, response) {
var user;
findUserByEmail(request.params.mail).then(_user => {
user = _user;
return user.relation("canHave").query().first();
// I left your relation query in here. In general, you don't
// have to query before removing it, but maybe your app logic requires this
// in other words, you could just do the remove and save here, and skip the next then block
}).then(event => {
if (event) user.relation("canHave").remove(event);
return user.save(null, { useMasterKey: true });
}).then(() => {
response.success();
}).catch(error => {
response.error(error);
});
});