Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Array Attribute Type in Sails

I'm looking to use the sails attribute type 'array' in my app, but I can't find documentation for this anywhere.

I'd like to do the following:

module.exports = {
 attributes : {
  images: {
   type: ['string']
  },
  location: {
   type: ['float','float']
  }
 }
}

image is an array that will hold a list of image urls and location will hold 2 floats. Will this work in sail's? Else how can I get this to work. Thanks

PS: I'm working solely with MongoDB

like image 407
SamAko Avatar asked Dec 15 '22 04:12

SamAko


2 Answers

As of Sails 1.0 type array is no longer supported.

The type "array" is no longer supported. To use this type in your model, change type to one of the supported types and set the columnType property to a column type supported by the model's adapter, e.g. { type: 'json', columnType: 'array' }

SOLUTION ONE

Set up property to store an images array and a location array...

module.exports = {
  attributes : {
    images: {
      type: 'json',                           
      columnType: 'array'
    }
    location: {
      type: 'json',
      columnType: 'array'
    }
  }
}

SOLUTION TWO

A more elegant solution is to set up a single object to store both filename and location data

module.exports = {
  attributes : {
    images: {
      type: 'json'
    }
  }
}

Then in your controller you would store object properties as arrays...

let imageData = {
  filename: ["image1.jpg", "image2.jpg", "image3.jpg"],
  location: [154.123123, 155.3434234, 35.12312312]
};

Images.create({images:imageData});

Some issues when storing data to the json object is that a string like "image1.jpg,image2.jpg,image3.jpg" will store in MongoDb no worries... doh. Ensure that when POSTing you may need to split the data .split(',').

like image 106
Eli Peters Avatar answered Jan 06 '23 01:01

Eli Peters


sailsjs provide a function to solve your question,you can try this

module.exports = {
 attributes : {
  images: {
   type: 'string'
  },
  location: {
   type: 'json'
  }
 }
}
like image 25
Khanh Tran Avatar answered Jan 06 '23 02:01

Khanh Tran