balderdashy / sails

Realtime MVC Framework for Node.js
https://sailsjs.com
MIT License
22.84k stars 1.95k forks source link

sails waterline sort on number not working(sails-redis) #5235

Closed nithin-ideas2it closed 5 years ago

nithin-ideas2it commented 8 years ago

I am trying to do sort id which is numeric (integer)

Modal:

module.exports = { autoPK: false, attributes: { id: { type: 'integer', autoIncrement:true, primaryKey: true }, } }

Query:

mymodal.find().sort({id: 'asc'}).exec(function (err, res) { console.log(res) }); Data:

[ { id: '2', },{ id: '1'},{ id: '11' } ]

Actual result: sorted as string :(

[ { id: '1', },{ id: '11'},{ id: '2' } ]

Expected result: sort by id...

[ { id: '1', },{ id: '2'},{ id: '11' } ]

Can anybody help me out. Please..

Sorting on string working, but on number(interger).

Is there any with my query or issue with sails waterline criteria sort

Ryanc1256-zz commented 8 years ago

hmm, seems interesting. @particlebanana does waterline handle the sorting?

nithin-ideas2it commented 8 years ago

@Ryanc1256 i assume it supports https://github.com/balderdashy/sails/issues/1052

deefeloper commented 8 years ago

+1

nithin-ideas2it commented 8 years ago

I not sure how much I am correct on this, but as I went through the sails-redis adapter index and schema, few things are missing. while parsing the input data like '11' the method not worried about the data type.

Data like { id: 1 } and { id: '1'} is consider to be different even though in the model

type: 'integer

specified.

sails-redis/lib/database/index.js ...

self.schema.parse(name, record)

...

sails-redis/lib/database/schema.js Existing code:

for(var key in values) {
    if(!this._schema[name][key]) continue;
    switch(this._schema[name][key].type) {
      case 'date':
      case 'time':
      case 'datetime':
        values[key] = new Date(values[key]);
        break;
    }
  }

the above code will not help to sort if the value of field with value '11' where, the datatype actually defined as 'interger'

Updated code:

Schema.prototype.parse...
for(var key in values) {
    if(!this._schema[name][key]) continue;
    switch(this._schema[name][key].type) {
      case 'date':
      case 'time':
      case 'datetime':
        values[key] = new Date(values[key]);
        break;
      case 'integer':
        values[key] = parseInt(values[key]);
        break;
      case 'float':
        values[key] = parseFloat(values[key]);
        break;        
    }
  }

The above changes working for me. Make sure the values[key] is not null or empty :)

Ryanc1256-zz commented 8 years ago

@nithin-ideas2it do you want to make a pr? and i can add it in?

nithin-ideas2it commented 8 years ago

Yes, please check from your side once. if you feel the code I suggested is correct, then please add.