Question

How can I do something like:

sort('object.property')

(object is defined as type 'json' in the model)

with Waterline?

Note that I am using the latest stable build 0.9.~ which does not have associations yet.

Was it helpful?

Solution

A quick test showed the sails-mongo adapter allows sorting of JSON attributes out of the box (it is transparently reached to the mongo database).

First I created a blank controller and model using:

sails generate foo

Then I defined a data property with type json on my model:

module.exports = {
    attributes: {
        data: 'json'
    }
};

I created several objects by doing a HTTP POST with data like this (I increased the sort value):

{
    "data": {
        "sort": 1
    }
}

Afterwards I fetched my collection using this GET request:

http://localhost:1337/foo?sort=data.sort+desc

which will internally result in a call like

Foo.find().sort('data.sort desc').exec(callback);

The server response is now sorted by the given property:

[
    {
        "data": {
            "sort": 3
        },
        "createdAt": "2014-04-13T09:35:49.734Z",
        "updatedAt": "2014-04-13T09:35:49.734Z",
        "id": "534a5a7553f1e98e09d1d86b"
    },
    {
        "data": {
            "sort": 2
        },
        "createdAt": "2014-04-13T09:35:45.814Z",
        "updatedAt": "2014-04-13T09:35:45.814Z",
        "id": "534a5a7153f1e98e09d1d86a"
    },
    {
        "data": {
            "sort": 1
        },
        "createdAt": "2014-04-13T09:35:41.958Z",
        "updatedAt": "2014-04-13T09:35:41.958Z",
        "id": "534a5a6d53f1e98e09d1d869"
    }
]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top