Blog

How to Delete Persistent Objects Using Data Service API

by on September 1, 2019

Deleting an object in your Backendless Database using the Data Service API is just as easy as creating or updating one. If an object has relations, they are broken up and the related objects are not deleted. The sample below retrieves the first object from a table and deletes it.

Consider the following database table, which contains “Person” objects:

For the SDKs which support custom class-based persistence, there is a class representing objects stored in the database:

    package com.mbaas.sample;
    import java.util.Date;
    public class Person
    {
        public int age;
        public String name;
        public Date birthdate;
        public String objectId;
    }

    API example:

    final AsyncCallback deleteResponder = new AsyncCallback() {
       @Override
       public void handleResponse(Long timestamp) {
           Log.i(TAG, "Object removed at " + new Date(timestamp).toString());
       }
    
       @Override
       public void handleFault(BackendlessFault fault) {
           Log.e(TAG, fault.getMessage());
       }
    };
    
    Backendless.Data.of(Person.class).findLast(new AsyncCallback() {
       @Override
       public void handleResponse(Person person) {
           Log.i(TAG, "Loaded object. Name - " + person.name);
           Backendless.Data.of(Person.class).remove(person, deleteResponder);
       }
    
       @Override
       public void handleFault(BackendlessFault fault) {
           Log.e(TAG, fault.getMessage());
       }
    });

    import java.util.Date
    
    data class Person(var birthdate: Date? = null, var objectId: String? = null, 
      var age: Int = 0, var name: String? = null)

    API example:

    val deleteResponder = object : AsyncCallback {
       override fun handleResponse(timestamp: Long) {
           Log.i(TAG, "Object removed at ${Date(timestamp)}")
       }
    
       override fun handleFault(fault: BackendlessFault) {
           Log.e(TAG, fault.message)
       }
    }
    
    Backendless.Data.of(Person::class.java).findLast(object : AsyncCallback {
       override fun handleResponse(person: Person) {
           Log.i(TAG, "Loaded object. Name - ${person.name}")
           Backendless.Data.of(Person::class.java).remove(person, deleteResponder)
       }
    
       override fun handleFault(fault: BackendlessFault) {
           Log.e(TAG, fault.message)
       }
    })

    @interface Person : NSObject
    
    @property (strong, nonatomic) NSString *objectId;
    @property (strong, nonatomic) NSString *name;
    @property (strong, nonatomic) NSDate *birthdate;
    @property (nonatomic) NSInteger age;
    
    @end

    API example:

    DataStoreFactory *dataStore = [Backendless.shared.data of:[Person class]];
    [dataStore findLastWithResponseHandler:^(Person *person) {
        NSLog(@"Loaded object. Name - %@", person.name);
            
        [dataStore removeWithEntity:person responseHandler:^(NSInteger timestamp) {
            NSLog(@"Object removed at %@", [NSDate dateWithTimeIntervalSince1970:timestamp/1000]);
        } errorHandler:^(Fault *fault) {
            NSLog(@"Error: %@", fault.message);
        }];
            
    } errorHandler:^(Fault *fault) {
        NSLog(@"Error: %@", fault.message);
    }];

    @objcMembers class Person: NSObject {
        var objectId: String?
        var name: String?
        var birthdate: Date?
        var age: Int = 0
    }

    API example:

    let dataStore = Backendless.shared.data.of(Person.self)
    dataStore.findLast(responseHandler: { person in
        if let person = person as? Person {
            print("Loaded object. Name - \(person.name ?? "")")
        }
                
        dataStore.remove(entity: person, responseHandler: { timestamp in
            print("Object removed at \(Date(timeIntervalSince1970: TimeInterval(timestamp/1000)))")
        }, errorHandler: { fault in
            print("Error: \(fault.message ?? "")")
        })
                
    }, errorHandler: { fault in
        print("Error: \(fault.message ?? "")")
    })

    const Backendless = require('backendless')
    /*
     Or use `import Backendless from 'backendless'` for client side.
     If you don't use npm or yarn to install modules, you can add the following line
     <script src="//api.backendless.com/sdk/js/latest/backendless.min.js"></script>
     to your index.html file and use the global Backendless variable.
    */
    
    Backendless.initApp('YOUR_APP_ID', 'YOUR_JS_API_KEY')
    
    const PersonStorage = Backendless.Data.of('Person')
    
    const loadLastPerson = () => {
      return PersonStorage.findLast()
    }
    
    const deletePerson = person => {
      console.log(`Loaded object. Name - ${ person.name }`)
    
      return PersonStorage.remove(person)
    }
    
    const onSuccess = ({ deletionTime }) => {
      console.log(`Object removed at ${ new Date(deletionTime) }`)
    }
    
    const onError = error => {
      console.error('Server reported an error: ', error.message)
      console.error('error code: ', error.code)
      console.error('http status: ', error.status)
    }
    
    Promise.resolve()
      .then(loadLastPerson)
      .then(deletePerson)
      .then(onSuccess)
      .catch(onError)
    

    Backendless.Data.of("Person").findLast().then((person) {
     print("Loaded object. Name - ${person['name']}");
    
     Backendless.Data.of("Person").remove(entity: person).then((timestamp) {
       print("Object removed at ${DateTime.fromMillisecondsSinceEpoch(timestamp)}");
     });
    });

    Once an object is deleted, it is completely removed from the system.

    Leave a Reply