Search code examples
arangodbfoxx

Object Array data type


This AQL returns an object I would like to use.

const keys = db._query(aql`
    FOR huis IN test
    FILTER huis._key in ${req.queryParams.keys}
    RETURN {
        'key': huis._key,
        'adres': huis.adres,
        'postcode': huis.postcode,
        'plaats': huis.plaats
    }
`);

This returns this object:

[
  {
    "key": "374875",
    "adres": "Klaverstraat 7",
    "postcode": "2197GV",
    "plaats": "Leiden"
  }
]

Then I would like to take the key like so:

keys[0].key

This works in JavaScript when I make a fiddle but not in Foxx.

const test = [
  {
    "key": "374875",
    "adres": "Klaverstraat 7",
    "postcode": "2197GV",
    "plaats": "Leiden"
  }
]

console.log(test[0].key)

374875

Why does this return 'undefined' in Foxx but the correct data in a Fiddle?


Solution

  • This Foxx code:

    router.get('/', function (req, res) {
      const test = [
        {
          "key": "374875",
          "adres": "Klaverstraat 7",
          "postcode": "2197GV",
          "plaats": "Leiden"
        }
      ];
    
      console.log(test[0].key);
      res.status(200).send(test[0]);
    }, 'test1')
      .summary('test1')
      .description('test1');
    

    Returns via REST:

    {
      "key": "374875",
      "adres": "Klaverstraat 7",
      "postcode": "2197GV",
      "plaats": "Leiden"
    }
    

    Logs into the ArangoDB logs:

    374875

    When you are getting the data via a query, you need to make sure the query is completed before you read the contents of the result.

    Look at this code:

    router.get('/', function (req, res) {
      const keys = db._query(aql`
        FOR huis IN test
        FILTER huis._key == "374875"
        RETURN {
            'key': huis._key,
            'adres': huis.adres,
            'postcode': huis.postcode,
            'plaats': huis.plaats
        }
    `).toArray();
    
      console.log(keys[0].key);
    
      res.status(200).send(keys);
    
    }, 'test1')
      .summary('test1')
      .description('test1');
    

    Here the FILTER condition has been changed, and .toArray() is added after the query has executed. This makes sure the query is complete and then the contents of keys is as you'd expect.