Hi I am trying to insert and sort data at the same time but it is not working. Have someone experience with it?
My example code looks like this:
collection.insert({id:"224535353", type:postValue, date:new Date}, {safe:true},{$sort: { id: -1 }}, function(err, result){
console.log(result);
});
Solution:
The mistake was I tried to sort the same id's.
collection.find({id:req.session.loggedIn},{sort:{date:-1}}).toArray(function(err, posts) {
console.log(posts);
});
You sort on find not on insert. Basically you don't want to care how the data is stored and it's mongodbs problem to retrieve it sorted if you want it sorted so insert with
collection.insert({id:"224535353", type:postValue, date:new Date},
{safe:true},function(err, result){console.log(result);});
and later find sorted with
collection.find({}).sort({id:-1})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With