Search code examples
javascriptnode.jsjsonknex.js

Knexnest query not returning data in array even though this is what is expected


I have this knexnest query:

    const query = knex.select([
      'notes.id AS _id',
      'notes.note AS _note',
      'notes.timestamp AS _timestamp',
      'customers.id AS _customerId',
      'users.name AS _name',
      'products.id AS _productId',
      'tags.id AS _tags_tagId',
      'tags.title AS _tags_tagTitle',
      'tags.type AS _tags_tagType',
    ]).from('notes')
      .join('users', 'notes.user_id', 'users.id')
      .join('customers', 'notes.customer_id', 'customers.id')
      .leftJoin('products', 'notes.product_id', 'products.id')
      .leftJoin('note_tags', 'notes.id', 'note_tags.note_id')
      .leftJoin('tags', 'note_tags.tag_id', 'tags.id')
      .where('customers.id', customerId);

    return knexnest(query);

My response json looks like this:

{
  "id": 47,
  "note": "This is an updated1 note",
  "timestamp": "2019-07-12T15:17:27.281Z",
  "customerId": 111781,
  "name": "Paul",
  "productId": 1,
  "tags": {
    "tagId": 4,
    "tagTitle": "price",
    "tagType": "product"
  }
}

The problem is that the database returns more than one tag, only one is displayed. I'm expecting a response like this:

{
  "id": 47,
  "note": "This is an updated1 note",
  "timestamp": "2019-07-12T15:17:27.281Z",
  "customerId": 111781,
  "name": "Paul",
  "productId": 1,
  "tags": {[
    {
      "tagId": 4,
      "tagTitle": "price",
      "tagType": "product"
    },
    {
      "tagId": 5,
      "tagTitle": "quality",
      "tagType": "product"
    }
  ]}
}

Have I got something wrong in my query that is causing this?


Solution

  • Got it. I was missing double __ in the tags:

    'tags.id AS _tags__tagId',
    'tags.title AS _tags__tagTitle',
    'tags.type AS _tags__tagType'