Liam Potter Liam Potter - 4 months ago 22
MySQL Question

How can I get a list of a specified field from a Sails JS Waterline collection?

I have a MySQL table with a

url
column and I want to get a list of every
url
value in the table. Structure:

Structure

In PHP using Laravel I could have done something like this to get an array of every
url
column value:

$boards = Board::all()->lists('url');


However, I cannot figure out how to do this using Sails JS. I've noticed that find() without any argument gets every row in the database but I can't find anything in the documentation that would allow me to either get a list of the values for the
url
column or a way to iterate over the returned collection.

I've tried this:

var boards = Board.find().exec(function(error, _boards) {
if(error)
{
return response.negotiate(error);
}

return _boards;
});


However, I can't actually seem to iterate over the returned data.

Any thoughts?

EDIT:

Full HomepageController.js:

module.exports = {
index: function (request, response) {
var data = {
currentDate: (new Date()).toString(),
boards: Board.query('SELECT url FROM board', function (error, results) {
if (error) {
return response.negotiate(error);
}

return results;
})
};

return response.view('homepage', data);
}
};

Answer

You can use a raw .query() to select individual columns:

Board.query('SELECT url FROM board', function (err, results) { ... });

However, keep in mind that your data will still look like this:

[{url: 'row 1 value'}, {url: 'row 2 value'}, ...]