Search code examples
arraysjsonsails.jswaterline

Store and parse array in model in Waterline


Using the newest version of Waterline 0.13.1-6 standalone.

The array type no longer exist in this version. So I assume the way to store arrays is now to use the JSON type.

Sample of my model Model:

  attributes: {
    someArray: { type: 'json' }
  }

Problem: on an instance of Model, model.someArray is now a String. I should JSON.parse it each time I request one to get the values in the array. That's very not convenient and can obviously lead to errors.

Is there a built-in way in the new Waterline to make this clean (automatically parse JSON fields...)?


Solution

  • You are fine to use JSON as you are suggesting. No need to parse it, this is done automatically when you do your meta fetch or find. You can do

    YourModel.create({someArray: [1,2,3]}).meta({fetch: true}).then( out => { console.log(out.someArray[0]); //1; });

    I would have some other identifying attribute for finding it, like say myRef: {type: 'string'}

    Then you can do

    YourModel.find({myRef: 'something'}).limit(1).then( out => { console.log(out[0].someArray[1]); //2 });