2014-09-29 111 views
0

我曾希望为Parse.com添加一个保存后触发事件,通知我何时更新某类用户的帐户。在这种情况下,如果Parse.User中的列“user_ispro”为真,我希望在保存后通过电子邮件发送(此列为null或true)。我添加了下面的代码,但每次更新都会收到电子邮件,而不仅仅是我的查询。思考?Parse.com Cloud代码 - 保存后

Parse.Cloud.afterSave(Parse.User, function(request) { 
    var Mandrill = require('mandrill'); 

    query = new Parse.Query(Parse.User); 
    query.equalTo("user_ispro", true); 
    query.find({ 
     success: function(results) { 
      Mandrill.initialize('xxxx'); 
      Mandrill.sendEmail({ 
       message: { 
        text: "Email Text", 
        subject: "Subject", 
        from_email: "[email protected]", 
        from_name: "Test", 
        to: [{ 
         email: "[email protected]", 
         name: "Test" 
        }] 
       }, 
       async: true 
      }, { 
       success: function(httpResponse) { 
        console.log(httpResponse); 
        response.success("Email sent!"); 
       }, 
       error: function(httpResponse) { 
        console.error(httpResponse); 
        response.error("Uh oh, something went wrong"); 
       } 
      }); 

     }, 
     error: function() { 
      response.error("User is not Pro"); 
     } 
    }); 
}); 

回答

1

查询的成功回调总是执行(读取:查询成功时),几乎在每种情况下都是如此。当没有结果时,您希望查询失败,这是错误的假设。

您应该添加一个检查,如果结果为空,并且只有在有实际结果时触发电子邮件发送。如果出现错误,错误回调只会被触发,空的结果不是错误(显然)。

0

谢谢Bjorn,我结束了使用计数查询而不是查找。如果结果数量大于0,则发送电子邮件。还意识到我没有查询具体的objectId,所以这是我的最终代码:

Parse.Cloud.afterSave(Parse.User, function(request) { 
var Mandrill = require('mandrill'); 

query = new Parse.Query(Parse.User); 
query.equalto("objectId",request.object.id); 
query.equalTo("user_ispro", true); 
query.count({ 
    success: function(count) { 

     if (count > 0) { 
     Mandrill.initialize('xxxx'); 
     Mandrill.sendEmail({ 
      message: { 
       text: "Email Text", 
       subject: "Subject", 
       from_email: "[email protected]", 
       from_name: "Test", 
       to: [{ 
        email: "[email protected]", 
        name: "Test" 
       }] 
      }, 
      async: true 
     }, { 
      success: function(httpResponse) { 
       console.log(httpResponse); 
       response.success("Email sent!"); 
      }, 
      error: function(httpResponse) { 
       console.error(httpResponse); 
       response.error("Uh oh, something went wrong"); 
      } 
     }); 

    }, 
    else { 
     console.log("User is not Pro"); 
    } 
}); 
});