Using variable in Javascript callback

47 Views Asked by At

I'm using the solr npm package to query a solr instance, and nightwatchjs as my test framework.

What I'm looking to do is access a random solr entry (which I will then extract info from) from my solr index.

The issue I'm having however, is getting this random entry.

The (example) solr index info I'm querying looks like this;

<?xml version="1.0" encoding="UTF-8"?>
<response>

    <lst name="responseHeader">
      <int name="status">0</int>
      <int name="QTime">0</int>
      <lst name="params">
        <str name="q">*:*</str>
        <str name="rows">1</str>
        <str name="facet">on</str>
        <str name="_">1688396679511</str>
      </lst>
    </lst>
    <result name="response" numFound="1867" start="0">
      <doc>
        <str name="CmsPageId">wp-13</str>
        <str name="UniqueIdentifier">ParkersReview-13</str>
        <str name="PageUrl">/penelope/mclaren/gt/coupe/review/</str>
        <str name="PrimarySection">cars</str>
        <int name="MakeId">77092</int>

So what I thought I could do was get the numFound value, randomize this value, and then use this in the callback.

And my solr query code looks like this;

exports.car_reviews_settings = function(solrWpProdClient, callback) {
    var seoCrawlPathLinksColourQuery = solrWpProdClient.createQuery()
    .q('*:*')
    .start(0)
    .rows(1)

    solrWpProdClient.search(seoCrawlPathLinksColourQuery,function(err,obj) {
        if(err) {
            callback(err,null);
            callback(err,obj.response.docs.length > 0);
        }
        else {
            var numberOfEntries = obj.response.numFound;
            console.log(numberOfEntries)
            var randomEntry = Math.floor(Math.random()* numberOfEntries)
            console.log(randomEntry)
            callback(null, obj.response.docs[`${randomEntry}`]);
            console.log(obj.response.docs[`${randomEntry}`])
        }
    });
};

The numFound is correctly displaying 1867. The random part is also working, as I get a random number for randomEntry.

However, I get an undefined for the obj.response.docs[`${randomEntry}`] part of the output.

Is obj.response.docs[`${randomEntry}`] the correct code for this, or is there something else I should be doing in order to get this working within the callback?

Thanks

0

There are 0 best solutions below