0

I want to sort the result of the mongodb query I was doing some practice on it but I can't get the result as it was expected to do so here is the code

ro.find(function(err,objs){ 
    if(err) res.write('{"Find Error":"'+err.err+'"}');
    else {
        // Get our data from the collection store
        objs.sort(date).toArray(function(error, items)
                            {`
            if(error)res.write('{"Find Error":"'+error.err+'"}');
            else{
               res.write(JSON.stringify(items));
               es.end();
            }
        });
    }
});//
Stennie
  • 63,885
  • 14
  • 149
  • 175
Bilal Naqvi
  • 140
  • 1
  • 11

2 Answers2

2

You can already sort in query as follow,

ro.find().sort({date : 1}).exec( function(err, result){
if(err)
res.write('{"Find Error":"'+error.err+'"}');
else{
      res.write(JSON.stringify(result));
      res.end();
    }
});

if you want to order ascending , you have to set

date : 1

but you need descending ,need to change

date : -1

It works for me

Soe Naing Tun
  • 375
  • 4
  • 10
0

You might look for MongoDB's sort method.

This and this previous questions might contain the solution to your problem. In this way, you have to move the callback that handles the data from the find method to the sort.

Community
  • 1
  • 1
fstab
  • 4,801
  • 8
  • 34
  • 66