Start a new topic

How to return a value from a Collection Access?

Hi All,

I am new to Kinvey but have some experience with Javascript. 

I am trying to return the value of a collection access find query, as I do not want to complete the response inside of the collection access function. I keep getting "undefined" as a result.

Does anyone know how I would resolve this?  Any help of guidance would be appreciated. Thanks!

function onPreSave(request, response, modules) {


  var testme = request.username;


  var getData = modules.collectionAccess.collection('user').findOne({"username": testme}, function (err, user) {


   {"null user");





      //This works!

      //response.body.hello = 'did it work: '+ user._id;


      // This does not?

      return user;      




  var finalResult = getData._id;


 //Why is finalResult "undefined"? 

  response.body.hello = 'did it work ' + " space " + finalResult;




Even when doing something like this I am still being returned "undefined".

var testme = request.username;  

var getID = modules.collectionAccess.collection('user').findOne({"username": testme});  

response.body.hello = 'did it work ' + " space " + getID._id;


Hi Stephen,

This is happening because modules.collectionAccess.collection('user').findOne is an asynchronous call and hence it won't return a value to getData variable. You need to keep using the code inside else block which works for you.

In your second reply, you removed the callback function which doesn't automatically make the function call synchronous.

Let me know if you have follow up questions about this.



Kinvey Support

Login or Signup to post a comment