Search code examples
javascriptdatabasebusiness-logickinvey

How do I delete old objects from collection with Kinvey Business Logic?


I have a collection called 'Events' at Kinvey and each event has a string formatted date to compare with current date. For example, I created the event "Party" and it has a startDate and endDate (iOS App). I want a custom Endpoint to delete the events that are not currently in this interval.

endDate looks like this: "2016-06-15 01:39:26 +0000" I used modules.moment() to get current date and tried to compare with the endDate. If modules.moment() is greater than endDate, the event gets deleted from the db.

I want a custom EndPoint because this method will run scheduled all the time to always check if an event has ended. My knowledge on javascript is really poor and I tried many examples, but I don't seem to be even close to the solution.


Solution

  • Sandor,

    Here is template code for your custom endpoint that might help you get started:

    function onRequest(request, response, modules) {
        var logger = modules.logger;
        var events = modules.collectionAccess.collection('Events');
        var moment = modules.moment();
    
        events.remove({"endDate" : {"$lt": moment.toISOString()}},
            function(err,res)
            {
                if(err)
                    {
                    logger.error("Error " + err);
                    return response.error(err);
                    }
                    else
                    {
                    return response.complete(200);
                    }
        });
    }
    

    Once you test this business logic thoroughly, you can then schedule it using the “Schedule” option for this custom endpoint in the Kinvey Dashboard.

    Thanks, Pranav Kinvey Support