Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose: Sorting by id

mongo db reorders the documents when ever a document is updated. I dint want this to happen so I found that using order by _id would return the documents in consistent order. But now I am not able to sort. Below is my find query which finds posts created by a particular user and I am trying to sort by _id. Code:

app.get('/posts/:user_id',function(req,res){

posts.find({
    'creator.user_id':req.params.user_id
},[],{ sort: { '_id': -1 } },function(err,userpost){
    if(err)
        res.send(err);
    res.json(userpost);


})

});
like image 548
roshan Avatar asked Jun 26 '14 17:06

roshan


People also ask

What is the difference between id and _ID in mongoose?

So, basically, the id getter returns a string representation of the document's _id (which is added to all MongoDB documents by default and have a default type of ObjectId ). Regarding what's better for referencing, that depends entirely on the context (i.e., do you want an ObjectId or a string ).

What is sort in mongoose?

sort() takes an object as parameter where the values are 1 or -1. Use -1 for descending order and 1 for ascending.


1 Answers

The second parameter is for the fields to select. You need to add options to the third parameter:

posts.find({'creator.user_id': req.params.user_id}, null, {sort: {'_id': -1}}, function(err,userpost) {
    if(err)
        res.send(err);
    res.json(userpost);
});

Alternatively you can use the sort() function:

posts.find({'creator.user_id': req.params.user_id}).sort({'_id': -1}).exec(function(err,userpost) {
    if(err)
        res.send(err);
    res.json(userpost);
});

You can find more examples in the documentation.

like image 154
Gergo Erdosi Avatar answered Oct 03 '22 18:10

Gergo Erdosi