javascriptnode.jsknex.jsadonis.js

How to save an array using AdonisJs migrations?


I'm trying to save an array to a PostgreSQL database, but I can't!

'use strict'

const Schema = use('Schema');

class UsersSchema extends Schema {
  up () {
    this.create('users', (table) => {
      table.increments();
      table.string('name', 255).notNullable();
      table.string('languages', 255).notNullable().defaultTo('[]');
      table.timestamps();
    });
  }

  down () {
    this.drop('users');
  }
}

module.exports = UsersSchema;

I tried to save like a string, like an array and use JSON.parse(), but it doesn't work


Solution

  • First of all your datatype is wrong, Adonisjs provides "json" datatype for a particular column. Solution:-

    1. Change column type from string -> JSON

    2. In the model, set datatype of "types" column as "string"

    3. How to write a query?

      a) You need to use a seeder to insert the data

      b) You have to write beforeSave() hook, and then using JSON.stringify() stringify your "types" so that the database can accept it.

      c) To retrieve data, write afterFetch() and afterFind() hook to parse your JSON string to normal JSON.