Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Bookshelf.js results with .orderBy()

I am working on a personal project to learn Node.js + express + Bookshelf.js. Where do I build queries? In particular, how do I simply set an 'ORDER BY' or 'WHERE' in the following code?

var Accounts = require('../collections/accounts').collection;

new Accounts().fetch({
    withRelated: ['folders']
}).then(function(collection) {
    // process results
});

I would like to learn Bookshelf.js because it seems to offer the features I am used to with Laravel's Elequent (PHP), such as polymorphic relationships and sub expressions. However, I'm finding that the documentation is not very in-depth and trying to find examples is near impossible.

Thanks in advance for any help.

Robin

like image 202
user1094128 Avatar asked Feb 27 '14 12:02

user1094128


Video Answer


2 Answers

Ah just found the answer to my question.

As the bookshelf.js website says, it uses knex.js query builder. So to sort my collection this is what I have done:

var Accounts = require('../collections/accounts').collection

new Accounts().query(function(qb){
    qb.orderBy('name','DESC'); 
}).fetch({

}).then(function(collection){
    // process results
});

... which works great!

like image 71
user1094128 Avatar answered Oct 21 '22 08:10

user1094128


You can also simply do

var Accounts = require('../collections/accounts').collection;

new Accounts().query('orderBy', 'columnname', 'asc').fetch({
    withRelated: ['folders']
}).then(function(collection) {
    // process results
});

without getting to the query builder.

like image 35
Vahe Hovhannisyan Avatar answered Oct 21 '22 07:10

Vahe Hovhannisyan