1

I want to insert an array of strings in one column of a postgresql table using waterline ORM of sailsjs.

I have tried making the model Users.js like this :

 interest:{
      type: 'string',
      required: false,
      columnType: 'array'
    }

The insert query goes like this:

Users.create({ interest : ['programming'] });

The datatype in postgre table for interest column is character varying[].

When i try to perform an insert using this setup, it throws an error:

 Specified value (a array: [ 'programming' ]) doesn't match the expected type: 'string'

how can I insert an array in the postgresql table, how should the model look like?

Any help would be appreciated, thanks!

7
  • You can use curly braces when inserting an array into a postgres db. So have you tried stringifying the array before creating it. For example, Users.create({interest : JSON.stringify(['programming'])}) Commented Apr 8, 2019 at 10:30
  • @Glen It gives an error malformed array literal Commented Apr 8, 2019 at 10:32
  • 1
    How about Users.create({interest : JSON.stringify(['programming']).replace(/\[/g, '{').replace(/]/g, '}')}). Very ugly though :) Commented Apr 8, 2019 at 10:42
  • @Glen Thanks, It works fine.But I think there could be a more proper way of doing that. Commented Apr 8, 2019 at 11:19
  • 1
    Had a quick look into the code, can you try changing the attribute type to json, interest: { type: 'json', required: false, columnType: 'array' } and just pass like Users.create({ interest : ['programming'] }); Commented Apr 8, 2019 at 13:54

1 Answer 1

3

I use PG arrays quite a bit throughout my projects and have never had any issues using type: 'ref' then specifying a postgres array type in columnType. Something like the following:

 things: {
  type: 'ref',
  columnType: 'text[]',
  defaultsTo: null, // or defaultsTo: []
  description: 'An array of stringy-things',
},

PG array type docs: https://www.postgresql.org/docs/9.1/arrays.html, but basically you want probably want to use <TYPE>[] for your columnTypes, ie integer[], etc

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.