Start a new topic

Local variable is undefined ?

function onRequest(request, response, modules)

{





var objectFound;



var findPatern = { "deviceID" : "ABC12345" };



function onReceiveData( error, retrievedEntity )

{

if( error )

{

return response.error(error);

}



if( retrievedEntity === null )

{

return response.error('No matching entity found.');

}

else

{

objectFound = retrievedEntity; // it will have some data



//response.body = objectFound;

//response.complete(200);

}

};



var db = modules.collectionAccess.collection('Clients');



db.findOne( findPatern, onReceiveData );



response.body = objectFound; // the data inside objectDound is undefined now ?!

response.complete(200);





}



objectFound is getting results, but it becaming undefined once it leave the body of the function onReceiveData.

Why, and how to set a local variable then ?

@Yordan‌



I'm not sure I understand what you mean by "escape pointless queries". The handler is the second parameter in the call to `db.findOne`
Oww... this is very unfortunately, since there has to be a way to escape pointless queries.

If there is no handler or something, maybe this have to be placed as a Bug. :|
@Yordan‌,



`onReceiveData` is called asynchronously when the `findOne` operation is successful. `findOne` is not blocking. You are calling `response.body = objectFound` before the object has actually been found. To fix this, continue your logic from within `onReceiveData`.



```

function onRequest (request, response, modules) {

var objectFound;

var findPatern = { "deviceID" : "ABC12345" };



function onReceiveData (error, retrievedEntity ) {

if ( error ) {

return response.error(error);

}

if (retrievedEntity === null ) {

return response.error('No matching entity found.');

}

else {

objectFound = retrievedEntity;

response.body = objectFound;

response.complete(200);

}

};



var db = modules.collectionAccess.collection('Clients');

db.findOne(findPatern, onReceiveData );

}

```
Login or Signup to post a comment