Start a new topic

Unable to delete entity with business logic on or off

The issue started when trying to update an entity, it would not let me, with business logic enabled or disabled, I have tried using REST API, Console Data Explorer and Consoles API Console, ios/android do not work either.

 

There is no business logic Pre/PostDelete BL. just onSave.

I have tried to by pass business logic. I have tried to update from the context of master key and user context with the same issue. I have gone as far as deleting business logic completely and trying all of the above again with no results.

 

When i update via the masker key context (tested in the the data explorer) it creates a new entity but the old entity remains unchanged

 

The concern is that I am currently requiring to update these entries on a regular basis and so deleting is not an option for the long term.

 

The Undeletable Entity Example is in collection "Vehicles":

5747fde2868c4766071da59b

...

if i retrieve the entire collection (i.e. dont specify a id perameter in the get request i get the following)

 

[..., 
 {
    "_id": "5747fde2868c4766071da59b",
    "registrationIndex": "LN63RFE",
    "registration": "LN63 RFE",
    "make": "VOLKSWAGEN",
    "model": "Polo Match Edition",
    "bodyType": "5 Door Hatchback",
    "color": "WHITE",
    "yearOfManufacture": 2013,
    "dateOfFirstRegistration": "ISODate(\"2013-09-05T00:00:00.000Z\")",
    "fuelType": "PETROL",
    "exportMarker": false,
    "revenueWeight": {
      "value": 1550,
      "unit": "kg"
    },...
]


when i DO specify the id (i.e. to return just the one entity) I get the following response (suggesting the entity DOES exist):

{
  "_id": "5747fde2868c4766071da59b",
  "registrationIndex": "LN63RFE",
  "registration": "LN63 RFE",
  "make": "VOLKSWAGEN",
  "model": "Polo Match Edition",
  "bodyType": "5 Door Hatchback",
  "color": "WHITE",
  "yearOfManufacture": 2013,
  "dateOfFirstRegistration": "ISODate(\"2013-09-05T00:00:00.000Z\")",
  "fuelType": "PETROL",
  "exportMarker": false,
  "revenueWeight": {
    "value": 1550,
    "unit": "kg"
  },
  "vehicleTypeApproval": "M1",
  "wheelPlan": "2 AXLE RIGID BODY",
  "CO2Emissions": {
    "value": 128,
    "unit": "g/km"
  },
  "cylinderCapacity": {
    "value": 1198,
    "unit": "cc"
  },
  "tax": {
    "valid": true,
    "sorn": false,
    "expiryDate": "ISODate(\"2016-09-01T00:00:00.000Z\")"
  },
  "mot": {
    "valid": true,
    "firstTestBy": "ISODate(\"2016-09-05T00:00:00.000Z\")"
  },
  "_acl": {
    "creator": "5747fc958ec79c046eee3d2c"
  },
  "_kmd": {
    "lmt": "2016-05-27T07:57:22.575Z",
    "ect": "2016-05-27T07:57:22.575Z"
  }
}



however when I try to delete i get:

DELETE /appdata/kid_WJ2I6ONgRl/Vehicles/5747fde2868c4766071da59b

Authorization: Basic a2lkX1dKMkk2T05nUmw6ZGIyMzlhYmE5Y2U5NGVjNGI4N2VmNTU1OTIyZTQ2OWM=
X-Kinvey-API-Version: 3
================
 
HTTP/1.1 404 NOT FOUND
Sat Jun 25 2016 04:23:51 GMT+0100 (GMT Summer Time)
 
Content-Type: application/json
X-Kinvey-API-Version: 3
X-Kinvey-Request-Id: d6b945f5daf8488aa4198586982ae4c4
X-Powered-By: Express
 
{
  "error": "EntityNotFound",
  "description": "This entity not found in the collection",
  "debug": ""
}

when i try to update (with all logic in place) i get the following error: - quick explaination, upon update, the original record is found and compared values, this error occurs only because the original record cannot be found using business logic;

 

PUT /appdata/kid_WJ2I6ONgRl/Vehicles/5747fde2868c4766071da59b
 
Authorization: Basic a2lkX1dKMkk2T05nUmw6ZGIyMzlhYmE5Y2U5NGVjNGI4N2VmNTU1OTIyZTQ2OWM=
X-Kinvey-API-Version: 3
 
{"registration":"LN63RFE"}
================
 
HTTP/1.1 400 BAD REQUEST
Sat Jun 25 2016 04:33:38 GMT+0100 (GMT Summer Time)
 
Content-Type: application/json
X-Kinvey-API-Version: 3
X-Kinvey-Request-Id: 56009e9146a546afabb143e3a0452f2b
X-Powered-By: Express
 
{
  "error": "BLRuntimeError",
  "description": "The Business Logic script has a runtime error. See debug message for details.",
  "debug": "TypeError: Cannot read property 'registration' of null",
  "stack": "TypeError: Cannot read property 'registration' of null\n  at Vehicles/onPreSave:86:55"
}

 

This issue only occurs with this entity and no others, and I have iterated through almost 100 records successfully to test this, and also with the same exact data as this entity.

 

Please advise how this can be resolved as it is critical.


Hi Sagar,


I am looking into this for you.


Can you tell me how this entity was created for the first time - CSV upload, BL code, kinvey console? 



Regards,

Wani

Kinvey Support

@wani -- this looks to be related to the ObjectID vs string ID issue. I see that the entity in the database has a string _id, whereas in the user's business logic code, he is first converting the incoming ID to an ObjectID before searching. I assume that he created the entity through BL at some point (or modified it before saving through the pre-save hook), but did not use the Kinvey module (http://devcenter.kinvey.com/rest/reference/business-logic/reference.html#kinvey-module), and thus ended up with a string _id.


This is also the reason he's unable to delete the entity -- when we get a request to delete by ID, we try to convert it to an ObjectID, and only use the string version if that conversion fails. Since in this case the string can be converted, the code searches for an entity with a matching ObjectID _id field, and finds none.


He could remove the entity by writing a one-time BL custom endpoint that uses the collectionAccess remove method to remove it -- something like collectionAccess.collection("Vehicles").remove({"_id":"5747fde2868c4766071da59b"}).

Hi Aniruddha Wani,


This was created via BL on save, the logic is simple a single parameter string is sent to kinvey and then BL makes a couple of API calls and then auto populates additional fields.


Hi Kinvey Support,


Your solutions to Delete the record works correctly! Thanks for the quick fix! I understand that a string ID and object id are two strictly different types but am not sure where i am going wrong. i have scanned my BL code and found the only place I consider ObjectID is on update (PUT). On creating a new entity, (POST) i simply see if the parameter "registration" is unique.


 When updating, I use the following to convert to objectId,

modules.collectionAccess.objectID(request.entityId)

and then use the following to find the entity 



  

  	  modules.collectionAccess.collection(request.collectionName).findOne({"_id": modules.collectionAccess.objectID(request.entityId)}, {}, function(err, doc){
  	   
  	    if (err){
...
          response.complete(400); 
  	      
  	    } else {
...         
          processVehcileInformation();
          
  	    }   
  	    
  	  });
  	  
  	}

 Full code for testing "POST/PUT"

if (request.method === "POST") {
  
    if (typeof request.body.registration === 'undefined' || request.body.registration === null || request.body.registration === ""){
      response.body.error = "vehicle registration missing";
      response.body.description = "Vehicle registration is a mandatory";
      response.body.debug = 'A vehicle registration must be provided in the body of the request with the key: "registration"';
      response.complete(400);	  
  	} else {
  	  tempObjectStore.set('registrationIndex', request.body.registration.replace(" ", "").toUpperCase());
    	delete request.body.registration;
  	}
      
    modules.collectionAccess.collection(request.collectionName).findOne({registrationIndex: tempObjectStore.get('registrationIndex'), _acl:{creator:modules.requestContext.getAuthenticatedUserId()}},{} , function (error, result){
      
      if (error) {

        response.body.debug = error;
        response.complete(500);
        
      } else {
        
        if (result === null){

          processVehcileInformation();
          
        } else {
                    
          response.body.error = "Conflict";
          response.body.description = "Vehcile with registration: " + result.registration + ", already added";
          response.body.debug = "You must delete this registration before you can add it again";
          response.complete(400);            

        }
        
      }
      
    });
    
  } else if (request.method === "PUT") {
      
    if (request.entityId !== null) {
      
  	  modules.collectionAccess.collection(request.collectionName).findOne({"_id": modules.collectionAccess.objectID(request.entityId)}, {}, function(err, doc){
  	   
  	    if (err){
  	      modules.logger.warn(err);
          response.body.error = "Unable to update";
          response.body.description = "ObjectId doesnt exists";
          response.body.debug = "ObjectId doesnt exists, refresh and try again";
          response.complete(400); 
  	      
  	    } else {
          
          tempObjectStore.set('registrationIndex', doc.registration.replace(" ", "").toUpperCase());
          processVehcileInformation();
          
  	    }   
  	    
  	  });
  	  
  	}

  }

 

are you able to advise where I am going wrong? as at no other point in my BL do i make reference to ObjectID/EntityID, can i also confirm that ObjectID and EntityID are the same thing?


Hi Sagar,

Is it possible that the entity you first mentioned (with id 5747fde2868c4766071da59b) was created through business logic at some point, through some code that is no longer used, maybe during development?

Are you seeing this issue with other entities? if not, or if it's just with a few, then perhaps the above is true. If you're seeing the same issue with new entities, then I'd suggest trying to figure out under what conditions this occurs to try and narrow down the cause.

As for your last question -- the answer is not exactly. ObjectID is a specific type used by MongoDB (our backing data store) to store ID values. The request.entityId property is simply a value we populate with the _id of the incoming entity.

Hope this helps!
Login or Signup to post a comment