Reputation: 185
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);
});
Upvotes: 3
Views: 3028
Reputation: 2940
I'm not quite sure of what you're trying to achieve here or if you're using monk or but mongodb doesn't return a collection or even an array of docs when doing an insert. It just returns a writeResult, as you can see here.. http://docs.mongodb.org/manual/reference/method/db.collection.insert/
What you CAN do is do the insert and then run a find query, like so...
collection.insert({id:"224535353", type:postValue, date:new Date}, {safe:true}, function(err, writeResult){
collection.find({},{sort:{id:-1}}, function(e, result){
console.log(result)
})
});
Upvotes: 0
Reputation: 3198
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})
Upvotes: 2