Start a new topic

onprefetch() collection.find() not working

To create an HTTP GET REST API, I have created an empty datastore & on prefetch(terminated with response.complete() rather than response.continue() so that it serves GET). I needed to construct a response by checking the other datastore tables.

================================================================================

function onPreFetch(request, response, modules) {

var count;

modules.collectionAccess.collection('datastore').find({"size": 10}}, function(err, fileDocs){

    count = fileDocs.length();

    if(!err){

      logger.info("run through fileDocs");

    } else {

      logger.info("error");

    }

  });

response.body = {"count":10} // Need to use "count" in place of 10

response.complete(); // TO PROVIDE HTTP GET only

}

================================================================================


For the code above, I am not getting any log responses. Any help would be appreciated.


Hi,


The find() call is asynchronous. So. the last two lines should be put at the end of the callback function. In the current code, response is sent even before find() completes executing.


Also, a couple of other errors are there in the above code. E.g. logger should be referenced as "modules.logger" and the query parameter in find() '{"size": 10}}' is malformed.


I have edited, tested above code and put it below:

   

function onPreFetch(request, response, modules) {
  var count;
  modules.collectionAccess.collection('datastore').find({}, function(err, fileDocs){
    count = fileDocs.length;
    if(!err){
      modules.logger.info("run through fileDocs");
    } else {
      modules.logger.info("error");
    }
    response.body = {"count":count}
    response.complete();
  });
}

 

I would recommend taking a look at following tutorials to learn more about business logic and using collection hooks effectively:



Regards,

Wani

Hmm, Thanks for the quick response. That did the trick.

Login or Signup to post a comment