2014-02-20 156 views
2

我想清除所有超過一天的對象....因此我使用了下面給出的雲代碼。 我的項目中有很多類,但下面的代碼僅適用於類「消息」。 即,Parse.Object.extend(「Messages」)中提到的類名稱。刪除Parse.com中的所有舊對象

我想遍歷項目中的所有類並刪除超過1天的數據。 如何迭代我的項目中的所有類併爲每個類運行相同的代碼?

// Use Parse.Cloud.define to define as many cloud functions as you want. 
// For example: 

Parse.Cloud.job("deleteOldEntries", function(request, status) {  
var yourObject = Parse.Object.extend("Messages"); 
var query = new Parse.Query(yourObject);  
var day = new Date(); 
day.setDate(day.getDate() - 1);  
query.lessThan("createdAt", day);  
    query.find 
    ({ 
      success:function(results) 
      { 
       for (var i = 0, len = results.length; i < len; i++) 
       { 
        var result = results[i]; 
        result.destroy(); 
        console.log("Destroy: "+i); 
       } 
      status.success("Delete successfully.");    
      }, 
      error: function(error) 
      { 
      status.error("Uh oh, something went wrong."); 
      console.log("Failed!");   
      } 
    })  
}); 

回答

1

「你只能執行雲代碼異步操作的數量有限。通過調用一個循環,你可能會遇到這種限制的destroy()反覆。」 - Hector From Parse

我建議首先你的雲代碼轉換爲「工作」,讓您的超時是15分鐘VS 15秒,然後更換destroy()方法有:

myObject.destroy({ 
    success: function(myObject) { 
    // The object was deleted from the Parse Cloud. 
    }, 
    error: function(myObject, error) { 
     // The delete failed. 
     // error is a Parse.Error with an error code and description. 
    } 

}); 

,等待繼續爲您刪除,直到你已經收到回調。

+0

你是什麼意思將雲代碼轉換爲「工作」? – 2014-08-27 23:37:26

+0

@ user3961466 - https://parse.com/docs/cloud_code_guide#jobs-writing – Logan

3

使用此代碼非常有幫助。

Parse.Cloud.job("deleteMessages", function(request, status) 

Parse.Cloud.useMasterKey(); 

var ts = Math.round(new Date().getTime()/1000); 
var tsYesterday = ts - (24 * 3600); 
var dateYesterday = new Date(tsYesterday*1000); 

var query = new Parse.Query("Your Object Class"); 

query.lessThan("createdAt", dateYesterday); 

query.find({ 
    success: function(result) { 
     for(var i=0; i<result.length; i++) { 
      result[i].destroy({ 
       success: function(object) { 
        status.success("Delete job completed"); 
        alert('Delete Successful'); 
       }, 
       error: function(object, error) { 
        status.error("Delete error :" + error); 
        alert('Delete failed'); 
       } 
      }); 
     } 
     status.success("Delete job completed"); 
    }, 
    error: function(error) { 
     status.error("Error in delete query error: " + error); 
     alert('Error in delete query'); 
    } 
}); 
});