Order records in DESC not working property in SequelizeJS
The working sample is:
// await Product.bulkCreate([ ... ])const results = await Product.findAll({ where: { type: 'a' }, limit: 10, order: [['updateDetails.time', 'DESC NULLS LAST']]});
Note that updateDetails
must be of JSONB type.
Order query is translated to:
ORDER BY ("Product"."updateDetails"#>>'{time}') DESC NULLS LAST LIMIT 10;
Try as follows.
const results = await Product.findAll({ where: { type: 'a' }, limit: 10, order: [['updateDetails.time', 'DESC NULLS LAST']] })
Well, if nothing works, you always have an option to sort this in plain JavScript :)
var data =[ { name: 'Product 1', type: 'a', updateDetails: { time: '2020-05-28T05:53:31.540Z', userId: 1, officeId: 2 } }, { name: 'Product 2', type: 'a', updateDetails: null }, { name: 'Product 3', type: 'a', updateDetails: { time: '2020-05-27T05:53:31.540Z', userId: 1, officeId: 2 } }, { name: 'Product 4', type: 'a', updateDetails: null }, { name: 'Product 5', type: 'a', updateDetails: { time: '2020-05-20T05:53:31.540Z', userId: 1, officeId: 2 } }]data.sort((a,b)=>{ if(a.updateDetails && !b.updateDetails){ return -1 } return a.name - b.name;});console.log(data)