Search code examples
javascriptarraysknex.js

How to select the first element of a column of type array column using knex.select()?


We are able to select the first element of a column of type array in Postgres SQL database. But I'm not able to query the same using knex.

I have tried this.

database('items')
    .select({icon: 'images[0]})
    .then(data => {
    res.send(data) 
}

Expecting the first element of images column of items table.


Solution

  • Try using the first() function. It returns the first row in your table (in whatever order the table is sorted). The .select('images') will limit the columns returned to just images.

    knex
      .select('images')
      .table('items')
      .first()
      .then((data) => {
        // first row of 'images' is an array.
        // return only the first item in array.
        res.send(data[0]);
    })