deyles-zz / sculejs

SculeJS - data structures for the web
165 stars 24 forks source link

Newbie problem with sorting #21

Closed thomaswb closed 11 years ago

thomaswb commented 11 years ago

I'm not sure what I'm doing wrong, but I can't seem to get sorting working. It always returns data in the order in which it was saved into the database. So this code:

collections.ingredients.find( {}, {$sort:{title:1}});

gives this result from some dummy data, in the order Flour, Butter, Sugar as entered:

[{"id":1,"title":"Flour","summary":"Some stuff","_id":{"id":"5199ead7a925f71f1a0c6e0e","$type":"id"}},{"id":2,"title":"Butter","summary":"Some other stuff","_id":{"id":"5199ead7a925f71c7e080932","$type":"id"}},{"id":3,"title":"Sugar","summary":"Some more stuff","_id":{"id":"5199ead7a925f7267d0dfe54","$type":"id"}}]

I'm using 'scule+titanium://' as the scheme, in Titanium on iOS, and it is saving and retrieving data OK.

What am I missing?

deyles-zz commented 11 years ago

Hey Thomas,

To do what you're attempting to do you need to perform an alphabetical sort. All sorted fields are treated as numbers unless otherwise specified.

To sort in ascending order:

var collection = sculedb.factoryCollection('scule+dummy://ingredients'); 
collection.save({"id":1,"title":"Flour","summary":"Some stuff"});
collection.save({"id":2,"title":"Butter","summary":"Some other stuff"});
collection.save({"id":3,"title":"Sugar","summary":"Some more stuff"});
collection.explain({i:{$gt:1}}, {$sort:{'title':1}});
var o = collection.find({}, {$sort:{title:2}});
console.log(o);

And in descending order:

var collection = sculedb.factoryCollection('scule+dummy://ingredients'); 
collection.save({"id":1,"title":"Flour","summary":"Some stuff"});
collection.save({"id":2,"title":"Butter","summary":"Some other stuff"});
collection.save({"id":3,"title":"Sugar","summary":"Some more stuff"});
collection.explain({i:{$gt:1}}, {$sort:{'title':1}});
var o = collection.find({}, {$sort:{title:2}});
console.log(o.reverse());
thomaswb commented 11 years ago

Thanks! That works.