我需要在解析云代码中编写beforeDelete函数,并且有多个查询 以下代码将删除所有注释,但不删除图像
注意:Post对象有2列(Relation和Relation) 图像和注释是自定义类
e.g。
Parse.Cloud.beforeDelete("Post", function(request, response) {
// delete all its comments
const commentsQuery = new Parse.Query("Comment");
commentsQuery.equalTo("postId", request.object.get("objectId"));
commentsQuery.find({ useMasterKey: true })
.then(function(comments) {
return Parse.Object.destroyAll(comments,{useMasterKey: true});
})
.catch(function(error) {
response.error("Error finding comments line 91 " + error.code + ": " + error.message);
});
// delete all its images
const postQuery = new Parse.Query("Post");
postQuery.equalTo("postId", request.object.get("objectId"));
// postQuery.include("images");
postQuery.first({useMasterKey: true})
.then(function(aPost){
var images = aPost.relation("images");
images.query().find({useMasterKey: true}).then(function(foundImages){
return Parse.Object.destroyAll(foundImages,{useMasterKey: true});
}).catch(function(error){
response.error("Error finding images line 107 " + error.code + ": " + error.message);
});
})
.catch(function(error) {
console.error("Error finding related comments " + error.code + ": " + error.message);
response.error("Error finding post line 113 " + error.code + ": " + error.message);
});
response.success();
});
2018-03-19T00:33:50.491Z - beforeDelete failed for Post for user undefined:
Input: {"User":{"__type":"Pointer","className":"_User","objectId":"LZXSK7AwE7"},"Content":"","Title":"ios ui, coffee shop app","isPublic":true,"createdAt":"2017-11-23T06:37:55.564Z","updatedAt":"2018-03-19T00:32:30.180Z","views":2,"images":{"__type":"Relation","className":"Image"},"mainColors":{"__type":"Relation","className":"Color"},"Comments":{"__type":"Relation","className":"Comment"},"objectId":"3UDJCIXxGS"}
Error: {"code":141,"message":"Error finding images line 107 undefined: A promise was resolved even though it had already been resolved."}
如何解决此问题以成功销毁其所有图像和评论
答案 0 :(得分:0)
我建议将代码重新组织成更小的可测试函数,承诺返回函数,类似这样......
function commentsForPost(postId) {
const commentsQuery = new Parse.Query("Comment");
commentsQuery.equalTo("postId", postId);
return commentsQuery.find({ useMasterKey: true })
}
function destroy(objects) {
return Parse.Object.destroyAll(objects,{useMasterKey: true});
}
function imagesForPost(post) {
let images = post.relation("images");
return images.query().find({useMasterKey: true});
}
现在,beforeDelete函数清晰简单......
Parse.Cloud.beforeDelete("Post", function(request, response) {
// get the post's comments
let post = request.object;
return commentsForPost(post.id)
.then(comments => destroy(comments))
.then(() => imagesFromPost(post))
.then(images => destroy(images))
.then(() => response.success());
});